I have simple app to build sql query (for educational purposes). I created textarea where user can write his command to sql, then program has to execute it or catch Sqlexeption. I know about safety etc. but its ok- user can delete everything :)
ok. here is the code:
query = text from textarea(its SQL command)
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");
}
}
And now, when im trying:
SELECT * FROM test its OK. GridView showing data.
slleeeccct * from testsste its OK - showing an error.
INSERT INTO test (col1) VALUES ('aaa') its NOT OK- program throws error System.IndexOutOfRangeException: cannot find table 0 BUT command was excecuted properly BUT TWICE.
Now i have a questions: why command is excecuting TWICE(2x same data in DB) and why is there an Error about finding table 0 (is it about GridView maybe- cant fill GV with insert into)?
SqlCommand.ExecuteScalarand then you're using the same command with aSqlDataAdapterand asking that adapter to fill a dataset... which it's going to do be executing the command again. Why are you callingExecuteScalarat all?ExecuteScalaris probably spurious and may be safely removed. (as he stated, theSqlDataAdapterwill execute the command itself)INSERT/UPDATE/DELETEandSELECTon the fronted as separate functions. Because how can youSELECTfrom anINSERTstatement ? Not possible. So when the perform any ofC U Dyou will need to run a separateSELECTand fill your datagrid.queryvariable in the SqlCommand, and never look at the command's .Parameters collection, you're missing that mechanism.