【发布时间】: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 < ds.Tables[typetable].Rows.Count 更改为 counter > 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