UPDATE sql表值

时间:2014-06-09 21:48:23

标签: c# sql

我有以下表格:

enter image description here

我希望更新每个单元格,用户可以定义。

我有以下代码:

 private void button3_Click_1(object sender, EventArgs e)
    {                                                                              
        string columnName = textBox8.Text;
        string IDNum = textBox7.Text;


        using (SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
        {
            try
            {
                SqlCommand cm = new SqlCommand();
                cm.Connection = cn;

                //as was the update statement
                cm.CommandText = "UPDATE ProduktTable SET " + columnName + " = " + textBox2.Text + " WHERE Id = @id";
                //clear all parameters insert statements uesd
                cm.Parameters.Clear();
                SqlParameter sp_update_col1 = new SqlParameter();
                sp_update_col1.ParameterName = "@id";
                sp_update_col1.SqlDbType = SqlDbType.VarChar;
                sp_update_col1.Value = IDNum;
                cm.Parameters.Add(sp_update_col1);
                //
                cn.Open();
                cm.ExecuteNonQuery();
                cn.Close();

             }
            catch (Exception ex)
            {
                MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

关键是,用户可以在定义columnName后更新所需的单元格,该名称可以是(Navn,Varenr,Antal,Enhed,Priseksklmoms,Konto)和Id值。 textBox2.Text定义新值,该值替换特定单元格中的旧值。我迷失了,以找到如何处理这个问题的程序。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

试试这个

cm.CommandText = "UPDATE ProduktTable SET [" + columnName + 
                 "] = @newValue WHERE Id = @id";
cm.Parameters.Clear();

SqlParameter sp_update_key = new SqlParameter();
sp_update_key.ParameterName = "@id";
sp_update_key.SqlDbType = SqlDbType.VarChar;
sp_update_key.Value = IDNum;
cm.Parameters.Add(sp_update_key);

SqlParameter sp_update_value = new SqlParameter();
sp_update_value.ParameterName = "@newValue";
sp_update_value.SqlDbType = SqlDbType.VarChar;
sp_update_value.Value = textBox2.Text;
cm.Parameters.Add(sp_update_value);
cn.Open();
cm.ExecuteNonQuery();
cn.Close();

原始代码中的问题是没有用单引号括起来的值(假设你的所有列都是varchar数据类型)这样解析器认为你有一个名为'Hans'的列而不是用作值的字符串。

使用参数应该可以解决问题。

说,请记住,您的查询不安全。它存在sql注入的风险,因为恶意用户可以在文本框中写入任何内容,包括可能破坏数据库的sql命令。

至少在表名周围放置方块,应该渲染(一点点)sql注入更难。 更安全的方法是不让您的用户键入列名,但强迫他/她从DropDownList中选择列名。