【问题标题】:I need help on IF EXIST ELSE我需要关于 IF EXIST ELSE 的帮助
【发布时间】:2019-12-08 05:41:27
【问题描述】:

我需要这方面的帮助

string query = @"IF EXISTS(Select * From u_Data Where TAG = '" + txtTag.Text + "') begin Update u_data set Name = '" + txtNama.Text +
                "', NIK = '" + txtNIK.Text + "', Department = '" + txtDept.Text + "' where Tag = '" + txtTag.Text +
                "' end else begin Insert Into u_data (TAG, Name, NIK, Department) VALUES ('" + txtTag.Text + "', '" + txtNama.Text + "', '" + txtNIK.Text + "', '" + txtDept.Text + "') end";
SqlCommand cmd = new SqlCommand(query, con);

根本无法更新 & 只会插入

【问题讨论】:

  • 尝试在 SQL 管理工作室中使用适当的值运行相同的查询。它在那里运行成功吗?
  • Bobby Tables 刚刚要求添加部门');drop table department;--。但我莫名怀疑他的诚意?顺便说一句,还有一个 MERGE 声明用于 upserts。

标签: c# sql-server sqlcommand


【解决方案1】:

运行这样的查询可能会导致 SQL INJECTION

你应该

  • 在查询中使用参数-
  • 创建一个查询来处理服务器上的IF EXISTS() 部分

试试这个代码:

    string query = @"IF EXISTS(SELECT * FROM u_Data WHERE TAG = @Tag)
                        UPDATE u_data SET NIK = @Nik, Department = @Department 
                        WHERE TAG = @Tag
                        ELSE
                        INSERT INTO u_Data (TAG, Name, NIK, Department) VALUES(@Tag, @Name, @Nik, @Department);";

    //create connection and command in "using" blocks
    using (SqlConnection conn = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        cmd.Parameters.Add("@Tag", SqlDbType.VarChar, 100).Value = txtTag.Text;
        cmd.Parameters.Add("@Name", SqlDbType.VarChar, 200).Value = txtName.Text;
        cmd.Parameters.Add("@Nik", SqlDbType.VarChar, 100).Value = txtNIK.Text;
        cmd.Parameters.Add("@Department", SqlDbType.VarChar, 100).Value = txtDept.Text;
        // open connection, execute query, close connection
        conn.Open();
        int rowsAffected = cmd.ExecuteNonQuery();
        conn.Close();
    }

【讨论】:

    【解决方案2】:

    尝试使用像实体框架或 NHibernate 这样的 ORM。简单干净。

    【讨论】:

      猜你喜欢
      • 2015-03-13
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多