如何将ac#datetime var插入SQL Server

ric*_*ard 2 c# sql-server asp.net 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();
Run Code Online (Sandbox Code Playgroud)

时间是smalldatetime在SQL Server 2005中

当我运行此程序时,会发生如下错误:

在此上下文中不允许使用名称"strDate".有效表达式是常量,常量表达式和(在某些上下文中)变量.不允许使用列名.

但如果我代替strDate2010/05/22这样的:

string strInsert = "insert into notepad (time, event) values ("2010/05/22", strEvent )";
Run Code Online (Sandbox Code Playgroud)

该程序将正确运行.

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

mar*_*c_s 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();
}
Run Code Online (Sandbox Code Playgroud)

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

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