使用参数查询的问题

时间:2011-06-10 17:33:19

标签: c# sql

我正在尝试将我的SQL查询切换到参数查询,但我在下面的代码后面显示了一些错误:

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");
        }
    }

错误信息是:

  

2 个答案:

答案 0 :(得分:3)

“date”是一个SQL保留字,因此SQL的转换可能会遇到问题。一般来说,您应该避免单独使用单词date作为列名或参数。

答案 1 :(得分:2)

就个人而言,我首先会丢失@[two word]变量名称(在其他地方也用作[@two word])。我不知道这是不是原因,但我个人从未见过这种用法,而且我很怀疑。适用于名称(和表名),但变量?不太确定。更改变量名称是此代码的本地名称,因此不应导致任何副作用。