gpt4 book ai didi

c# - SQL 命令不工作

转载 作者:行者123 更新时间:2023-12-02 04:53:33 27 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/

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