这是代码:
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".有效表达式是常量,常量表达式和(在某些上下文中)变量.不允许使用列名.
但如果我代替strDate用2010/05/22这样的:
string strInsert = "insert into notepad (time, event) values ("2010/05/22", strEvent )";
Run Code Online (Sandbox Code Playgroud)
该程序将正确运行.
我对这个问题感到困惑,并向你寻求帮助.