I wrote the following code, but nothing is being inserted into the database.
I tried changing the SA password in the connection string to something incorrect and the code isn’t catching the exception.
What am I doing wrong?
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(); }
Advertisement
Answer
As stated by the OP in the comments. Once the try-catch
was resolved it was discovered that it just a mismatched number of fields and values.
Just an FYI, you can get rid of this:
USE CollegeRecruiting
It’s already using the right database because of the connection that you created above it.
Finally, please don’t leave yourself open to SQL Injection. Rewrite your code to be something more along these lines:
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(); }