我编写了以下代码,但没有将任何内容插入数据库。
我尝试将连接字符串中的 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();
}