我有簡單的應用程序來建立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
)?
那麼你打電話'SqlCommand.ExecuteScalar'然後你使用相同的命令與之前閱讀一個'SqlDataAdapter'並要求該適配器填充數據集。 ..它將會再次執行命令。你爲什麼要調用'ExecuteScalar'呢? –
那麼,要執行命令:),那麼我應該怎麼打電話? – Kafus
@Kafus,我想喬恩暗示對'ExecuteScalar'的調用可能是虛假的,可能會被安全地刪除。 (正如他所說的那樣,'SqlDataAdapter'將自己執行命令) –