尝试将int变量插入SQL Server表

时间:2017-04-13 04:34:12

标签: c# sql-server

protected void addItem_Click(object sender, EventArgs e)
{
    String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        string PID;
        Button oButton = (Button)sender;
        PID = oButton.CommandArgument.ToString();

        int productId = Convert.ToInt32(PID);
        Debug.Write(productId);

        string email = (string)(Session["email"]);

        SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

当我的查询执行时,我收到错误

  

列名称无效' productId'

正如您所看到的,我已将字符串转换为整数变量,我已打印出变量以检查它返回的内容。它确实按预期返回一个int,但由于一些奇怪的原因,我无法插入到我的表中。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:5)

希望productId不是basket表的主键。

然后,而不是

 SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);

如下修改

 SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( @productId,@email)", con);
cmd.Parameters.Add(new SqlParameter("@productId",productId );
cmd.Parameters.Add(new SqlParameter("@email",email );

为什么建议修改是为了避免SQLInjection攻击。如果您不知道这一点,请浏览以下链接并了解它

https://en.wikipedia.org/wiki/SQL_injection

答案 1 :(得分:1)

这里有两个问题,第一个和一个大问题,参数化该查询!您正在使用类似代码打开SQL注入攻击。

第二个是你实际上没有传入你的productId变量,你告诉它使用productId列的值 - 这也是你要插入的列。

SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (@productId, @email)");
cmd.Parameters.AddWithValue("@productId", productId);
cmd.Parameters.AddWithValue("@email", email);

我无法强调将用户输入转储到将直接在数据库上运行的SQL是多么危险。