C#/sql用swl参数更改sql参数

本文关键字:sql 参数 swl | 更新日期: 2023-09-27 18:23:42

我在以c#形式使用SQL时遇到问题,我希望有人能帮助我这里是代码,我写为!!!来!!!到问题的行。

我想检查文本框,如果它们是空的,我会把旧的变量放在更新函数中,但我无法在新旧命令之间进行均衡。参数

     private void button2_Click(object sender, EventArgs e)
        {
            string sql = "Update faculty SET fcode=@fcode,fname=@fname,foundationdate=@foundationdate WHERE fcode=@fcodeold";
            try
            {
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.AddWithValue("@fcode", textBox1.Text);
                command.Parameters.AddWithValue("@fname", textBox2.Text);
                command.Parameters.AddWithValue("@foundationdate", dateTimePicker1.Value);
                command.Connection = connection;
              //  command.CommandText = "DELETE FROM faculty WHERE fcode=@fcode";
                command.Parameters.AddWithValue("@fcodeold", dataGridView1.CurrentRow.Cells[0].Value.ToString());
                command.Parameters.AddWithValue("@fnameold", dataGridView1.CurrentRow.Cells[1].Value.ToString());
                command.Parameters.AddWithValue("@foundationdateold", dataGridView1.CurrentRow.Cells[2].Value.ToString());
                if (textBox1.Text =="") command.Parameters.["@fcode"].Value= command.Parameters.("@fcodeold").Value;
    //!!!HERE!!!
                if (textBox2.Text == "") command.Parameters.AddWithValue("@fname", "@fnameold");
                if (dateTimePicker1 == null) command.Parameters.AddWithValue("@foundationdate", "@foundationdateold");
                command.ExecuteNonQuery();
                connection.Close();
                MessageBox.Show("Updating success", "Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                FormFaculty_Load(null, null);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

C#/sql用swl参数更改sql参数

为什么要这样设置参数?:

command.Parameters.["@fcode"].Value = command.Parameters.("@fcodeold").Value

您已经拥有"值",因为您以前使用过它:

command.Parameters.AddWithValue("@fcodeold", dataGridView1.CurrentRow.Cells[0].Value.ToString())

只需以相同的方式设置此参数:

command.Parameters.AddWithValue("@fcode", dataGridView1.CurrentRow.Cells[0].Value.ToString())

不要试图从查询中设置值。数据在一个地方,查询在另一个地方。根据数据设置查询值。


总结:

删除代码中先前设置参数的位置:

command.Parameters.AddWithValue("@fcode", textBox1.Text); // remove this line

并根据您的逻辑有条件地设置参数:

if (textBox1.Text =="")
    command.Parameters.AddWithValue("@fcode", dataGridView1.CurrentRow.Cells[0].Value.ToString())
else
    command.Parameters.AddWithValue("@fcode", textBox1.Text)