So apparently, ExecuteReader is used for read only and ExecuteNonQuery is used for transactions. But for some reason even when I used ExecuteReader I am still able to run write (Insert, Update, Delete) commands (typed in textbox1). Is there something wrong with my code or am I misunderstanding the way ExecuteReader is supposed to work?
//MY CODE
string sqlStatement = textbox1.Text;
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder.DataSource = ActiveServer;
builder.IntegratedSecurity = true;
System.Data.SqlClient.SqlConnection Connection = new
System.Data.SqlClient.SqlConnection(builder.ConnectionString);
Connection.Open();
System.Data.SqlClient.SqlCommand command = new
System.Data.SqlClient.SqlCommand(sqlStatement, Connection);
System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader();
dataGridView1.AutoGenerateColumns = true;
bindingSource1.DataSource = reader;
dataGridView1.DataSource = bindingSource1;
reader.Close();
Connection.Close();
ExecuteReadersimply returns a reader that can read rows returned from a SQL procedure – it doesn’t stop you from running arbitrary SQL on the way to providing that result set.Doing inserts / updates / deletes and then immediately returning a result set (so from code looking like a read) is arguably a little odd (read: code smell), and should be reviewed to see if it can be split into distinct actions.