Sql命令不起作用

本文关键字:不起作用 命令 Sql | 更新日期: 2023-09-27 18:28:42

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

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

Sql命令不起作用

如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();
}

删除INSERT语句之前的USE CollegeRecruiting

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

例如:

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

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

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

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

谢谢大家的帮助!

CJ