2014-05-14 19 views
0

我有使用MySQL連接與數據庫一起工作的WPF應用程序。我有一個特定的查詢,用於檢查我的輸入信息是否具有數據庫中已存在的唯一標識。如果確實如此,那麼我需要什麼都不做,但如果不需要,我需要在那裏插入一條新記錄。 下面是我有的代碼。問題是,在我嘗試創建並執行新命令的最後使用語句中,出現錯誤消息:「此連接已經存在一個開放的DataReader」。在打開的DataReader中執行另一個MySQL語句

通過它的外觀,我需要建立一個不同的連接和使用,而不是有一個使用當前連接的工作呢?

using (MySqlCommand checkCmd = con.CreateCommand()) 
{ 
    checkCmd.CommandText = "SELECT id FROM table WHERE id = @RFID"; 
    checkCmd.Parameters.AddWithValue("RFID", myValue); 

    using (MySqlDataReader reader = checkCmd.ExecuteReader()) 
    { 
     //if not found, then insert the new value in the database 
     if (!reader.Read()) 
     { 
       using (MySqlCommand cmd = con.CreateCommand()) 
       { 
        //try to create and execute insert query here 
       } 
     } 
    } 
} 
+0

爲什麼不使用現有的連接'con',並且不要創建另一個'cmd'? – gunr2171

+0

嘗試使用dataset/dataadapter(OR)創建一個將立即執行所有此任務的過程。 – Rahul

回答

2

在您的示例中,您可以簡單地關閉閱讀器並執行插入;

bool found; 

using (MySqlCommand checkCmd = con.CreateCommand()) 
{ 
    checkCmd.CommandText = "SELECT id FROM table WHERE id = @RFID"; 
    checkCmd.Parameters.AddWithValue("RFID", myValue); 

    using (MySqlDataReader reader = checkCmd.ExecuteReader()) 
    { 
     found = reader.Read(); 
    } 
} 

if(!found) { 
    using (MySqlCommand cmd = con.CreateCommand()) 
    { 
     //try to create and execute insert query here 
    } 
} 

如果id另一種可能的選擇應該是唯一的就是不要做id選擇可言,只是設置一個唯一索引,並使用INSERT IGNORE插入行,如果它不存在。

+0

@Rahul是的,當然,修好了,謝謝:) –

+0

謝謝,兩者都是很好的建議! – mmvsbg

2

另一種選擇是創建一個過程,將完成所有的任務又像

create procedure insertifnotexist @rfid int,@someothercolumn varchar(10) 
as 
begin 
declare @tabid int; 
SELECT @tabid = id FROM table WHERE id = @rfid; 
if(@tabid = '') 
insert into table values(@rfid,@someothercolumn); 
end 

然後從代碼中調用這個過程傳遞@RFID參數。

相關問題