Sql命令不起作用

时间:2013-08-22 14:57:49

标签: c# asp.net .net sql sqlconnection

我编写了以下代码,但没有任何内容插入到数据库中。

我尝试将连接字符串中的SA密码更改为不正确的代码并且代码没有捕获异常。

我做错了什么?

protected void Button2_Click(object sender, EventArgs e)
{
    firstName = TextBox1.Text;
    lastName = TextBox2.Text;
    collegeName = TextBox3.Text;
    majorSubject = TextBox4.Text;
    emailAddress = TextBox5.Text;
    phoneNumber = TextBox6.Text;
    address = TextBox7.Text;
    city = TextBox8.Text;
    state = DropDownList1.SelectedValue;
    zipCode = TextBox9.Text;
    interestDate = DateTime.Now.ToString("M/d/yyyy");

    string completedString = " " +firstName+ " "  +lastName+ " "  +collegeName+ " "  +majorSubject+ " "  +emailAddress+ " "  +phoneNumber+ " "  +address+ " "  +city+ " "  +state+ " "  +zipCode+ " " +interestDate+ ".";
    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + completedString + "');", true);

    try
    {

    string strCon = "Data Source=OMIW2310.orthman.local;Initial Catalog=CollegeRecruiting;User Id=sa;Password=myPassword;";
    using (var connection = new SqlConnection(strCon))
    {

        string strSQL = "USE CollegeRecruiting INSERT INTO Students (lastName, firstName, collegeName, majorSubject, emailAddress, phoneNumber, address, city, state, zip, interestDate) VALUES ('" + firstName + "', '" + lastName + "', '" + collegeName + "', '" + majorSubject + "', '" + emailAddress + "', '" + phoneNumber + "', '" + city + "', '" + state + "', '" + zipCode + "', '" + interestDate + "')";
        SqlCommand command = new SqlCommand(strSQL, connection);

        connection.Open();
        command.ExecuteNonQuery();
        connection.Close();

       } 
   }
   catch (SqlException ex)
   {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
   }

   ClearTextBoxes();        

}

3 个答案:

答案 0 :(得分:3)

正如OP在评论中所述。一旦try-catch得到解决,就会发现它只是一个不匹配的字段和值。

只是一个FYI,你可以摆脱这个:

USE CollegeRecruiting

由于您在其上方创建的连接,它已经在使用正确的数据库。

最后,请不要让自己接受SQL注入。将代码重写为更多内容:

using (SqlConnection c = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("INSERT INTO ... VALUES (@field1...)"), c)
{
    cmd.Parameters.AddWithValue("@field1", txtField1.Text);

    c.Open();
    cmd.ExecuteNonQuery();
}

答案 1 :(得分:2)

删除USE CollegeRecruiting声明前的INSERT

还使用parameterized查询来防止SQL注入攻击。

例如:

  command.CommandText = "INSERT INTO Students (lastName, firstName VALUES (@lastName, @firstname);";

  command.Parameters.AddWithValue("@lastName", lastName);
  command.Parameters.AddWithValue("@firstName", firstName);

注意:您在第一个名称列中输入last name,反之亦然。

答案 2 :(得分:0)

一旦我更正了catch语句,结果错误显示我的INSERTS / VALUES数量不匹配。

我现在将参数化我的查询以防止SQL注入攻击。

感谢大家的帮助!

CJ