我试图让我的代码尽可能小巧。SQL Server日期时间接受NULL
使用Microsoft SQL Server,.NET 2.0
我在我的数据库,接受空值
LeaseExpiry(datetime, null)
我抢的文本框的值,并将其转换为datetime日期字段。
DateTime leaseExpiry = Convert.ToDateTime(tbLeaseExpiry.Text);
INSERT_record(leaseExpiry);
我遇到的问题是如果提交表单并且文本框为空。我收到此错误:
字符串未被识别为有效的日期时间。
如何设置我的代码了,这样如果文本框为空,排在数据库创建NULL
?
我已经试过初始化我的变量设置为NULL,但得到一个错误在Visual Studio
DateTime leaseExpiry = null;
无法将null转换为“System.DateTime的”,因为它是一个非空的值类型。
这里的数据访问层是否有帮助
public string INSERT_record(DateTime leaseExpiry)
{
//Connect to the database and insert a new record
string cnn = ConfigurationManager.ConnectionStrings[connname].ConnectionString;
using (SqlConnection connection = new SqlConnection(cnn))
{
string SQL = string.Empty;
SQL = "INSERT INTO [" + dbname + "].[dbo].[" + tblAllProperties + "] ([LeaseExpiry]) VALUES (@leaseExpiry);
using (SqlCommand command = new SqlCommand(SQL, connection))
{
command.Parameters.Add("@leaseExpiry", SqlDbType.DateTime);
command.Parameters["@leaseExpiry"].Value = leaseExpiry;
}
try
{
connection.Open();
command.ExecuteNonQuery();
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
谢谢
应拼写'leaseExpiry'(不'leaseExpirey') - 你在你的代码,这是非常令人困惑的有两个版本。我一直把它固定为'Expiry'。 –