如何直接插入Identity列的值?

时间:2013-03-20 12:09:02

标签: c# asp.net database

我正在尝试通过此UI将值插入数据库。下面是代码。现在我希望ID列直接获取值(它的主键和我也在该列上设置了Identity)。接下来,应将所有其他值插入到数据库中的相应列中。现在发生了什么,名称文本框中的值转到ID列&它有点导致一个错误。我怎样才能实现我想要的?

enter image description here

  protected void btnRegister_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
        string strQuery = "Insert into AUser values ('"+ txtName.Text +"', '"+ txtEmailAddress.Text +"', '"+txtPassword.Text +"', '"+ ddlMobile.Text +"', '"+ ddlMobile.Text +"', '"+ txtMobileNumber.Text +"' )";
        SqlCommand Cmd = new SqlCommand(strQuery,con);
        con.Open();
        Cmd.ExecuteNonQuery();

enter image description here

5 个答案:

答案 0 :(得分:3)

更新的编写代码!

始终使用parameterized queries。此代码对 SQL Injection 攻击开放。

SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);      
string strQuery = "Insert into AUser(Name, Email, Password, CountryCode, Mobile, MobileNumber) values (@Name, @EmailAddress, @Password, @Mobile, @MobileNumber)";
SqlCommand Cmd = new SqlCommand(strQuery,con);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@EmailAddress", txtEmailAddress.Text);
cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
cmd.Parameters.AddWithValue("@Mobile", ddlMobile.Text);
cmd.Parameters.AddWithValue("@MobileNumber", txtMobileNumber.Text);
con.Open();
Cmd.ExecuteNonQuery();

BTW ,您在字符串命令中添加ddlMobile.Text两次。这可能是错误的。

您还没有使用CountryCode列..

答案 1 :(得分:2)

你应该构建你的sql语句,如:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

其中值应通过SQL参数填充。

另外,如果您想直接在ID列中获取值,为什么首先将其设置为Auto?

答案 2 :(得分:1)

您的查询必须像这样

 string strQuery = "Insert into AUser(Name,Email,Password,CountryCode,Mobile) values ('"+ txtName.Text +"', '"+ txtEmailAddress.Text +"', '"+txtPassword.Text +"', '"+ ddlMobile.Text +"', '"+ ddlMobile.Text +"', '"+ txtMobileNumber.Text +"' )";

答案 3 :(得分:1)

作为最佳实践,您应始终在insert子句中命名您的字段:

string strQuery = "Insert into AUser(name,email,password,countrycode,mobile) values ('"+ txtName.Text +"', '"+ txtEmailAddress.Text +"', '"+txtPassword.Text +"', '"+ ddlMobile.Text +"', '"+ ddlMobile.Text +"', '"+ txtMobileNumber.Text +"' )"

这种方式,如果你在表格中添加一个字段,你就不会破坏你的代码......

答案 4 :(得分:0)

最简单的方法是在插入查询中指定列名

Insert into AUser (Name, Email, [Password], CountryCode, Mobile)values (@Name, @Email,@Password, @CountryCode, @Mobile)

你的sql目前容易受到sql注入攻击。

添加像这样的参数值

SqlCommand Cmd = new SqlCommand(strQuery,con);
Cmd.Parameters.AddWithValue("@Name", txtName.Text);
...
con.Open();
Cmd.ExecuteNonQuery();