为什么这个特殊的INSERT语句会失败?

时间:2014-10-11 06:56:05

标签: c# sql sql-server ado.net

我正在尝试将我的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();

3 个答案:

答案 0 :(得分:1)

  1. 一个错误是使用txtpassword(即整个UI控件)作为SqlParameter的值。将其替换为txtpassword.Text(即输入到UI控件中的文本值):

    insert.Parameters.AddWithValue("@Password", txtpassword.Text);
    
  2. 您的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);
    //                                         ^
    

答案 1 :(得分:1)

insert.Parameters.AddWithValue("ID_Number", txtid.Text);

那应该是

insert.Parameters.AddWithValue("@ID_Number", txtid.Text);

答案 2 :(得分:0)

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);