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();
问问题
3253 次
1 回答
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);
.....
命令文本中的参数占位符将替换为同名参数的值,无需在参数占位符内添加空格使事情变得复杂。
于 2013-08-10T12:38:28.627 回答