我有一個問題,即如果我的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語句之外移動 –