为什么这个特殊的INSERT语句失败
本文关键字:INSERT 语句 失败 为什么 | 更新日期: 2023-09-27 18:26:16
我正试图将ASP.NET web应用程序中的数据插入SQL Server数据库表(我以前创建过该表)。我的代码似乎不起作用,显示了错误消息,实际数据似乎没有保存到数据库中。
var conn = new SqlConnection("Data Source=SHRIYA''SQLEXPRESS;Initial Catalog=…;Integrated Security=True");
var insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(@GenerateID,@Name,@Surname,@ID_Number,@Gender,@Address,@Postal_code,@Phone_Number,@Email,@Password", conn);
insert.Parameters.AddWithValue("@GenerteID",lstuserID.SelectedIndex);
insert.Parameters.AddWithValue("@Name", txtname.Text);
insert.Parameters.AddWithValue("@Surname", txtsurname.Text);
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
insert.Parameters.AddWithValue("@Gender", ddlgender.SelectedItem);
insert.Parameters.AddWithValue("@Address", txtaddress.Text);
insert.Parameters.AddWithValue("@Postal_code", txtpostalcode.Text);
insert.Parameters.AddWithValue("@Phone_Number", txttele.Text);
insert.Parameters.AddWithValue("@Email", txtEmail.Text);
insert.Parameters.AddWithValue("@Password", txtpassword);
try
{
conn.Open();
insert.ExecuteNonQuery();
}
catch (Exception)
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Error When Saving');", true);
}
conn.Close();
-
一个错误是使用
txtpassword
(即作为整体的UI控件)作为SqlParameter
的值。将其替换为txtpassword.Text
(即输入到UI控件中的文本值):insert.Parameters.AddWithValue("@Password", txtpassword.Text);
-
SQL命令文本缺少
VALUES (
:的右括号)
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address, Postal_code,Phone_Number,Email,Password) values(@GenerateID,@Name,@Surname,@ID_Number,@Gender,@Address, @Postal_code,@Phone_Number,@Email,@Password)", conn); // ^
insert.Parameters.AddWithValue("ID_Number", txtid.Text);
那应该是
insert.Parameters.AddWithValue("@ID_Number", txtid.Text);
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(@GenerateID,@Name,@Surname,@ID_Number,@Gender,@Address,@Postal_code,@Phone_Number,@Email,@Password", conn);
SQL语法错误。
最后一个参数@Password
缺少)
。
SqlCommand insert = new SqlCommand("Insert Into tblRegister(GenerateID,Name,Surname,ID_Number,Gender,Address,Postal_code,Phone_Number,Email,Password) values(@GenerateID,@Name,@Surname,@ID_Number,@Gender,@Address,@Postal_code,@Phone_Number,@Email,@Password)", conn);