C# 使用参数查询的问题
我试图将我的SQL查询转换为参数查询,但在下面的代码之后,我不断出现一些错误:C# 使用参数查询的问题,c#,sql,C#,Sql,我试图将我的SQL查询转换为参数查询,但在下面的代码之后,我不断出现一些错误: protected void btnSubmit_Click(object sender, EventArgs e) { if (Page.IsValid) { //Define data objects SqlConnection conn; //SqlCommand comm;
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (@Surname,[@Other Names],@mobileno,@date, @email, @faculty, @dept, [@Registration Number], @session,@thesis, @yearGrad, @tellerno, @amount, @address,@question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("@Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("@[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("@mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("@date", lblDate.Text);
cmd.Parameters.AddWithValue("@email", lblEmail.Text);
cmd.Parameters.AddWithValue("@faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("@dept", lblDept.Text);
cmd.Parameters.AddWithValue("@[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("@session", lblSession.Text);
cmd.Parameters.AddWithValue("@thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("@yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("@tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("@amount", lblAmount.Text);
cmd.Parameters.AddWithValue("@address", lblAdd.Text);
cmd.Parameters.AddWithValue("@question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
错误消息是:
“/TranscriptReload”应用程序中出现服务器错误。
“nvarchar”附近的语法不正确。
必须声明标量变量“@date”
“date”是SQL保留字,因此转换为SQL可能有问题。一般来说,您应该避免将单词date单独用作列名或参数。就我个人而言,我首先会丢失
@[two word]
变量名(您在其他地方也将其用作[@two word]
)。我不知道这是否是原因,但我个人从未见过这种用法,我对此表示怀疑。对于列名(和表名)很好,但是变量呢?不太确定。更改变量名是此代码的局部操作,因此不会产生任何副作用。tx伙计们,日期不是问题所在,Marc关于变量名的声明方式是正确的,我将它们更改为单个名称,并且有效。如果解决了您的问题,通常会接受答案!(数字下方左侧的勾号!)