我有一个问题,即如果我的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
,我可以增加价值,但我不能在数据库编辑/更新。
我认为您使用的是Microsoft SQL Server - 请确认,因为SQL实现之间的语法不同。 – STW
你需要阅读SQL注入,这是一个教科书的例子。您需要使用参数化查询。不要像select *一样检查行的存在。使用EXISTS。 –
'cmd.Connection = con;'可以在if语句之外移动 –