gpt4 book ai didi

c# - Sql 命令不起作用

转载 作者:行者123 更新时间:2023-12-02 21:52:08 24 4
gpt4 key购买 nike

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

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

}

最佳答案

正如OP在评论中所述。解决 try-catch 后,我们发现它只是字段和值的数量不匹配。

仅供引用,您可以摆脱这个:

USE CollegeRecruiting

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

最后,请不要让自己遭受 SQL 注入(inject)。将您的代码重写为更多这样的内容:

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

关于c# - Sql 命令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com