如果值存在则更新,否则在数据库中插入值

时间:2015-10-15 18:10:06

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

我遇到的问题是,如果我的textbox中有4个值 - 身份证,房间类型,费率,额外费用;如果数据库中存在“房间类型”,则更新,如果不存在则插入数据库。

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 < ds.Tables[typetable].Rows.Count更改为counter > ds.Tables[typetable].Rows.Count,我可以添加值,但我无法在数据库中进行编辑/更新。

1 个答案:

答案 0 :(得分:7)

您正在寻找的是&#34; UPSERT&#34;声明。 upsert结合了insert和update语句,并将执行相关操作。自MS SQL 2003以来它已经可用,但在引入MERGE功能的SQL Server 2008之前还没有完全出现。

这是代码示例,取自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注入。