|M| 第二贴: 更新数据库表问题:让表中一个日期型的字段为空"" 刚才的大家没有能理解我的意思
原贴:http://community.csdn.net/Expert/topic/5379/5379837.xml?temp=.4323694
原贴:http://community.csdn.net/Expert/topic/5375/5375628.xml?temp=.2727777
如我有表
user
id nameid indate outdate
2 11 2007-3-1 2007-3-1
3 23 2007-3-1
如上面是我的员工进出表要求的,员工进入时记得进入时间,员工离开时记得离开时间
然后以下代码:员工进入
void Insertuser(Int32 User,DateTime indate,DateTime outdate)
{
String sql=String.Format( "Insert into tab ([nameid],[indate],[outdate]) values ({0}, '{1} ', '{2} ') ",User,indate,outdate);
....这里添加记录
}
不要管我上面的这种写法是否错误,
我要的是如何用Insertuser能够向SQL添加一条outdate为空值的记录
也就是我现在要添加
27 2007-3-4
这样一条记录那么
Insertuser(27,Convert.ToDateTime( '2007-3-4 '),????)
那么里面的????要怎么来写呢
注:
Insertuser(Int32 User,DateTime indate,DateTime outdate)
这条过程是不能修改的也就是固定的不要改动的.
然后用Insertuser(27,Convert.ToDateTime( '2007-3-4 '),????)
也就是其他什么地方都不能改而????就是想问大家要怎么写的
我的主要想得到的是,如何将一个C#的DataTime变量,添加到SQL中为空值
------解决方案--------------------My IME got some problems, I can input chinese now.So I have to use ENG.
To achieve your target, you need to do:
1. when you define the outdate column make sure null value is allowed.
2. when you insert the recoed in C#, use DBNull.value as the value of your SQL parameter. In other words use DBNull.value instead of your ????.
------解决方案--------------------可空类型:
示例如下:
using System;
using System.Text;
using System.IO;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class ConsoleTest
{
public static void Main()
{
SqlConnection theCon = new SqlConnection();
SqlCommand theCmd = new SqlCommand();
string strCon = "Server=127.0.0.1;DataBase=TestDB;Integrated Security=SSPI ";
theCon.ConnectionString = strCon;
theCmd.Connection = theCon;
theCon.Open();
string strCmd = "INSERT INTO test VALUES(@ID,@NAME,@DATE) ";
theCmd.CommandText = strCmd;
theCmd.Parameters.Add( "@ID ", SqlDbType.Char, 1);
theCmd.Parameters.Add( "@NAME ", SqlDbType.VarChar, 10);
theCmd.Parameters.Add( "@DATE ", SqlDbType.DateTime);
theCmd.Parameters[0].Value = 'G ';
theCmd.Parameters[1].Value = "lizhizhe2000 ";
DateTime? mytime=null;
DBNull aa = System.DBNull.Value;
if (!mytime.HasValue)
theCmd.Parameters[2].Value = aa;
else
theCmd.Parameters[2].Value = mytime;
try
{
theCmd.ExecuteNonQuery();
Console.WriteLine( "OK,Close it ");
}
catch (Exception e)
{