2015-10-15 155 views
1

我有一個問題,即如果我的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.Countcounter > ds.Tables[typetable].Rows.Count,我可以增加價值,但我不能在數據庫編輯/更新。

+1

我認爲您使用的是Microsoft SQL Server - 請確認,因爲SQL實現之間的語法不同。 – STW

+4

你需要閱讀SQL注入,這是一個教科書的例子。您需要使用參數化查詢。不要像select *一樣檢查行的存在。使用EXISTS。 –

+0

'cmd.Connection = con;'可以在if語句之外移動 –

回答

7

你要找的是「UPSERT」語句。 upsert結合了插入和更新語句,並將執行相關操作。從MS SQL 2003開始就已經可以使用它,但是直到引入了MERGE函數的SQL Server 2008才能完全實現。

這是一個代碼示例,取自another answerThis 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注入。

+1

爲什麼人們不喜歡這個? – CSharpie

+0

答案可以通過顯示參數化查詢看起來像這個例子來改善......至少對於查詢部分。 –

相關問題