簡體   English   中英

SQL C#,命令(查詢)執行兩次

[英]SQL C#, command(query) is executing twice

我有一個簡單的應用程序來構建sql查詢(出於教育目的)。 我創建了textarea,用戶可以在其中將命令寫入sql,然后程序必須執行它或捕獲Sqlexeption。 我知道安全性等知識,但是可以的用戶可以刪除所有內容:)

好。 這是代碼:

查詢=來自textarea的文本(其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')的NOT OK-程序拋出錯誤System.IndexOutOfRangeException: cannot find table 0 BUT命令被正確執行了兩次。

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

首先,您要執行兩次代碼

->一次使用ExecuteScalar,另一次使用SQLAdapter用返回的結果填充數據集,則可以像下面這樣使用它:

1- dataset ds=new dataset();

2- adapter.fill(ds);

3- return ds; 

就是這樣:)

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

因此,當您使用Insert語句時,您會遇到錯誤,因為

1-命令未成功執行,並返回錯誤“檢查databsae是否具有您剛剛鍵入的插入行”

2-數據集表中沒有數據,您可以在嘗試從中讀取之前先進行IF語句檢查

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM