如何将c#datetime var插入SQL Server

时间:2011-05-23 03:30:51

标签: c# asp.net sql-server sqlcommand

以下是代码:

string ConnectionString= @"Data Source=localhost\SQLEXPRESS; 
Initial Catalog=notepad; Integrated Security=SSPI ";
SqlConnection con = new SqlConnection(ConnectionString); 
con.Open();
string strEvent = TextBoxEvent.Text;
string strDate = Calendar1.TodaysDate.ToShortDateString();
string strInsert = "insert into notepad (time, event) values (strDate, strEvent )";
SqlCommand cmd=new SqlCommand(strInsert, con);
cmd.ExecuteNonQuery();

SQL Server 2005中的时间是smalldatetime

当我运行此程序时,会出现如下错误:

  

不允许使用名称“strDate”   这个背景。有效的表达式是   常量,常量表达式和   (在某些情况下)变量。柱   不允许使用姓名。

但如果我将strDate替换为2010/05/22,请执行以下操作:

string strInsert = "insert into notepad (time, event) values ("2010/05/22", strEvent )";

程序将正常运行。

我对这个问题感到困惑,并向你寻求帮助。

3 个答案:

答案 0 :(得分:5)

您应该使用参数化查询将数据插入SQL Server,并且应该将SqlConnectionSqlCommand放入使用块中 - 尝试这样的事情:

string ConnectionString= @"Data Source=localhost\SQLEXPRESS; 
Initial Catalog=notepad; Integrated Security=SSPI ";

string sqlStatement = "INSERT INTO dbo.Notepad(time, event) VALUES (@Date, @Event)";

using(SqlConnection con = new SqlConnection(ConnectionString))
using(SqlCommand cmd = new SqlCommand(sqlStatement, con))
{
   cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = Calendar1.TodaysDate;
   cmd.Parameters.Add("@Event", SqlDbType.VarChar, 100).Value = TextBoxEvent.Text.Trim();

   con.Open();
   cmd.ExecuteNonQuery();
   con.Close();
}

此外,这是将您的数据库访问代码与您的UI代码混合(从文本框和日历控件中检索数据) - 这是一种不好的做法 - 您应该将其分为两个步骤:

  1. 从代码隐藏文件中的UI中获取当前值
  2. 将它们传递给处理数据访问的数据层,而无需直接触摸任何UI控件

答案 1 :(得分:2)

这里说的所有方法都很好,但我更喜欢以下方法,因为它比其他方法更具优势

DataAccess DAB = new DataAccess();
ArrayList arrList = new ArrayList();
string SQL = " insert into notepad (time, event) values (?,?) ";
arrList.Add(new DataAccessBlock.DataAccess.Parameter("@time",  DbType.DateTime, 30, ParameterDirection.Input, "", strDate ));    
arrList.Add(new DataAccessBlock.DataAccess.Parameter("@event", DbType.String, 50, ParameterDirection.Input, "", strEvent ));

DAB.ExecuteScalar(SQL, CommandType.Text, arrList);

答案 2 :(得分:1)

下面的陈述是错误的,因为您实际上包括strDate而不是替换它的值。

string strInsert = "insert into notepad (time, event) values (strDate, strEvent )";

您需要做的是写如下:

string strInsert = "insert into notepad (time, event) values ("+strDate+"," +strEvent+)";

这将在运行时将strDate和strEvent替换为实际值。

* 但不推荐使用此方法,因为它容易受到SQL注入攻击*