SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO Records ([Student ID], [First Name], [Last Name], " +
"[Middle Initial], Gender, Address, Status, Year, Email, Course, " +
"[Contact Number]) VALUES ( @Student ID, @First Name, @Last Name, " +
"@Middle Initial, @Gender, @Address, @Status, @Year, @Email, " +
"@Course, @Contact Number)";
SqlParameter p1 = new SqlParameter("@[Student ID]", SqlDbType.Int);
p1.Value = textBox1.Text;
cmd.Parameters.Add("1");
SqlParameter p2 = new SqlParameter("@First Name", SqlDbType.VarChar);
p2.Value = textBox2.Text;
cmd.Parameters.Add("p2");
SqlParameter p3 = new SqlParameter("@Last Name", SqlDbType.NVarChar);
p3.Value = textBox3.Text;
cmd.Parameters.Add("p3");
SqlParameter p4 = new SqlParameter("@Middle Initial", SqlDbType.NChar);
p4.Value = comboBox1.Text;
cmd.Parameters.Add("p4");
SqlParameter p5 = new SqlParameter("@Gender", SqlDbType.NChar);
p5.Value = comboBox2.Text;
cmd.Parameters.Add("p5");
SqlParameter p6 = new SqlParameter("@Address", SqlDbType.VarChar);
p6.Value = textBox4.Text;
cmd.Parameters.Add("p6");
SqlParameter p7 = new SqlParameter("@Status", SqlDbType.NChar);
p7.Value = comboBox3.Text;
cmd.Parameters.Add("p7");
SqlParameter p8 = new SqlParameter("@Year", SqlDbType.VarChar);
p8.Value = comboBox4.Text;
cmd.Parameters.Add("p8");
SqlParameter p9 = new SqlParameter("@Email", SqlDbType.VarChar);
p9.Value = textBox5.Text;
cmd.Parameters.Add("9");
SqlParameter p10 = new SqlParameter("@Course", SqlDbType.VarChar);
p10.Value = comboBox5.Text;
cmd.Parameters.Add("p10");
SqlParameter p11 = new SqlParameter("@Contact Number", SqlDbType.VarChar);
p11.Value = textBox6.Text;
cmd.Parameters.Add("p11");
cmd.ExecuteNonQuery();
con.Close();
答案 0 :(得分:3)
将参数的实例添加到集合中,而不是字符串“p11”
SqlParameter p11 = new SqlParameter("@ContactNumber", SqlDbType.VarChar);
p11.Value = textBox6.Text;
cmd.Parameters.Add(p11);
并且您不需要在参数名称中使用空格来改变您的生活。
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO Records ([Student ID], [First Name], [Last Name], " +
"[Middle Initial], Gender, Address, Status, Year, Email, Course, " +
"[Contact Number]) VALUES ( @StudentID, @FirstName, @LastName, " +
"@MiddleInitial, @Gender, @Address, @Status, @Year, @Email, " +
"@Course, @ContactNumber)";
.....
// Name your parameters without spaces
SqlParameter p1 = new SqlParameter("@StudentID", SqlDbType.Int);
p1.Value = textBox1.Text;
cmd.Parameters.Add(p1);
.....
命令文本中的参数占位符将替换为具有相同名称的参数值,无需复杂化在参数占位符内添加空格的内容。