【问题标题】:If value exists then update, else insert value in database如果值存在则更新,否则在数据库中插入值
【发布时间】:2016-01-14 07:50:35
【问题描述】:

我有一个问题,如果我的textbox 中有 4 个值 - ID、房间类型、房价、额外费用;如果数据库中存在房间类型,则更新,如果不存在,则插入数据库。

public void existRoomType()
{
    con.Open();
    string typetable = "tblRoomType";
    string existquery = "SELECT*FROM tblRoomType WHERE RoomType = '" + txtRoomType.Text + "'";
    da = new SqlDataAdapter(existquery, con);
    da.Fill(ds, typetable);
    int counter = 0;
    if (counter < ds.Tables[typetable].Rows.Count)
    {
        cmd.Connection = con;
        string edittypequery = "UPDATE tblRoomType SET RoomType = '" + txtRoomType.Text + "', RoomRate = '" + txtRateOfRoom.Text + "', ExtraCharge = '" + txtExtraCharge.Text + "', CancelFee = '" + txtCancelFee.Text + "', MaxOccupant = " + txtMaxOccupants.Text + "" +
            "WHERE TypeID = '" + txtTypeID.Text + "'";
        cmd.CommandText = edittypequery;
        cmd.ExecuteNonQuery();

        MessageBox.Show("Type of Room is added.", "Room Type Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    else
    {
        cmd.Connection = con;
        string addtypequery = "INSERT INTO tblRoomType VALUES ('" + txtTypeID.Text + "','" + txtRoomType.Text + "','" + txtRateOfRoom.Text + "','" + txtExtraCharge.Text + "','" + txtCancelFee.Text + "'," + txtMaxOccupants.Text + ")";
        cmd.CommandText = addtypequery;
        cmd.ExecuteNonQuery();

        MessageBox.Show("Type of Room is edited.", "Room Type Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    con.Close();
}

如果我将条件 if 语句从 counter &lt; ds.Tables[typetable].Rows.Count 更改为 counter &gt; ds.Tables[typetable].Rows.Count,我可以添加值,但我无法在数据库中编辑/更新。

【问题讨论】:

  • 我认为您使用的是 Microsoft SQL Server——请确认,因为 SQL 实现之间的语法不同。
  • 你需要阅读sql注入,这是一个教科书的例子。您需要使用参数化查询。并且不要执行 select * 之类的操作来检查是否存在行。使用 EXISTS。
  • cmd.Connection = con; 可以移到 if 语句之外

标签: c# sql-server if-statement sql-update sql-insert


【解决方案1】:

您要查找的是“UPSERT”语句。 upsert 结合了插入和更新语句,并将执行相关操作。它从 MS SQL 2003 开始​​可用,但直到 SQL Server 2008 才完全成熟,其中引入了 MERGE 函数。

这是一个代码示例,取自another answer。该答案还引用了This article,作为使用MERGE 语句的一个很好的介绍。

MERGE 
   member_topic AS target
USING 
   someOtherTable AS source
ON 
   target.mt_member = source.mt_member 
   AND source.mt_member = 0 
   AND source.mt_topic = 110
WHEN MATCHED THEN 
   UPDATE SET mt_notes = 'test'
WHEN NOT MATCHED THEN 
   INSERT (mt_member, mt_topic, mt_notes) VALUES (0, 110, 'test')
; 

这种方法的好处是它只需要一个 SQL 查询,而您当前的方法需要两个查询。它还避免了混合语言,这通常有利于可维护性。

您还应该使用Parameterized Queries 将变量值传递给SQL。这将为您提供防止 SQL 注入的保护。

【讨论】:

  • 可以通过显示此示例的参数化查询的外观来改进答案......至少对于查询部分。
猜你喜欢
  • 2017-09-27
  • 2015-12-17
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
相关资源
最近更新 更多