2016-11-14 55 views
0

我有簡單的應用程序來建立sql查詢(教育目的)。 我創建了textarea,用戶可以將他的命令寫入sql,然後程序必須執行它或捕獲Sqlexeption。我知道安全等,但其確定用戶可以刪除所有內容:)SQL C#,命令(查詢)正在執行兩次

好的。這裏是代碼:

查詢=文本從文本區域(其SQL命令)

if (!String.IsNullOrEmpty(query) || !String.IsNullOrWhiteSpace(query)) 
{ 
    string conString = ConfigurationManager.ConnectionStrings["StudentDataBase"].ConnectionString; 

    try 
    { 
     using (SqlConnection SqlCon = new SqlConnection(conString)) 
     {     
      try 
      { 
       SqlCommand command = new SqlCommand(query, SqlCon); 
       SqlCon.Open(); 

       command.ExecuteScalar(); 

       int numOfRows = 0; 

       SqlDataAdapter adpt = new SqlDataAdapter(command); 
       DataTable dt = new DataTable(); 
       DataSet dset = new DataSet(); 
       adpt.Fill(dset); 
       dt = dset.Tables[0]; 
       if (dt.Rows.Count > 0) 
       { 
        numOfRows = dt.Rows.Count; 
        gridview_results.DataSource = dt; 
        gridview_results.DataBind(); 

        Sql_error = "Done. Results: " + numOfRows + " rows."; 
        container_sql_error.Style.Add("background-color", "#b9ffcb"); 
       } 
       else 
       { 
        Sql_error = "0 rows to show."; 
       }       

       SqlCon.Close(); 
      } 
      catch (SqlException ex) 
      { 
       Sql_error = "Error: " + ex.Message; 
       container_sql_error.Style.Add("background-color", "#ff9600"); 
      } 
     } 
    } 
    catch (SqlException ex) 
    { 
     Sql_error = "Error... " + ex.Message; 
     container_sql_error.Style.Add("background-color", "#ff9600"); 
    } 
} 

而現在,當我嘗試:

SELECT * FROM test其確定。 GridView顯示數據。

slleeeccct * from testsste其確定 - 顯示錯誤。

INSERT INTO test (col1) VALUES ('aaa')其不正確 - 程序拋出錯誤System.IndexOutOfRangeException: cannot find table 0但是命令正確地執行了但是兩次。

現在我有一個問題:爲什麼命令執行TWICE(在數據庫中有兩個相同的數據),爲什麼會出現一個關於finding table 0的錯誤(關於GridView可能無法填充GV insert into)?

+1

那麼你打電話'SqlCommand.ExecuteScalar'然後你使用相同的命令與之前閱讀一個'SqlDataAdapter'並要求該適配器填充數據集。 ..它將會再次執行命令。你爲什麼要調用'ExecuteScalar'呢? –

+0

那麼,要執行命令:),那麼我應該怎麼打電話? – Kafus

+1

@Kafus,我想喬恩暗示對'ExecuteScalar'的調用可能是虛假的,可能會被安全地刪除。 (正如他所說的那樣,'SqlDataAdapter'將自己執行命令) –

回答

1

首先,您要執行的代碼兩次

- >一個你正在使用的ExecuteScalar和你使用的是SQLAdapter,以填補與返回的結果集的其它時間,你可以只使用它像下面:

1- dataset ds=new dataset(); 

2- adapter.fill(ds); 

3- return ds; 

,僅此而已:)

關於的櫻雪rt查詢錯誤,這也是正常的,因爲使用Execute Scalar的插入語句將執行查詢,並返回查詢返回的結果集中第一行的第一列。其他列或行將被忽略。

所以,當您使用Insert語句,你是因爲無論

1-命令未成功執行並返回一個錯誤「檢查databsae已插入的行剛纔鍵入」

有錯誤

2 - 數據集表中沒有數據,就可以讓一個if語句檢查您嘗試從它像

"If(ds.tables.count>0) {do something}" 
+0

謝謝。這正是我需要的。 – Kafus