2

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

我尝试将连接字符串中的 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();        

}
4

3 回答 3

3

正如评论中的OP所述。一旦try-catch解决了问题,就会发现它只是字段和值的数量不匹配。

仅供参考,你可以摆脱这个:

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();
}
于 2013-08-22T15:00:27.330 回答
2

去掉USE CollegeRecruiting前面的INSERT语句。

还使用参数化查询来防止 SQL 注入攻击。

例如:

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

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

注意:last name在名字列中输入,反之亦然。

于 2013-08-22T15:00:41.760 回答
0

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

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

谢谢大家的帮助!

CJ

于 2013-08-22T15:17:11.447 回答