如果值存在则更新,否则在数据库中插入值
本文关键字:数据库 插入 存在 更新 如果 | 更新日期: 2023-09-27 18:17:50
我有一个问题,如果我的textbox
- ID,房间类型,房价,额外收费的值为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
,我可以添加值,但我不能在数据库中编辑/更新
您要查找的是"UPSERT"语句。upsert结合了插入和更新语句,并将执行相关操作。自MS SQL 2003以来,它已经可用,但直到SQL Server 2008才完全成熟,其中引入了MERGE
函数。
下面是一个代码示例,取自另一个答案。这篇文章也被这个答案引用,作为使用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查询,而当前的方法需要两个查询。它还避免了混合语言,这通常有利于可维护性。
您还应该使用参数化查询将变量值传递给SQL。