Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A reader needs an open connection because you retrieve the results one at a time. You'll want to do an <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx" rel="noreferrer">ExecuteNonQuery()</a> for inserts, deletes and updates. You also need to close your connection afterwards. The alternative is to wrap your inserts into a loop if you plan to do multiple inserts.</p> <p>There are a couple of ways you can do this. This way is useful if you plan to reuse the same connection object and command object over and over again:</p> <pre><code>public partial class Form1 : Form { SqlConnection _cn; SqlCommand _cmd; const string ConnString = "Enter your connection string here"; readonly string _insertQuery; const string UsernameParm = "@username"; public Form1() { InitializeComponent(); _cn = new SqlConnection(ConnString); _cmd = new SqlCommand(InsertQuery, _cn); _cmd.Parameters.Add(UsernameParm, SqlDbType.VarChar); _insertQuery = String.Format("INSERT INTO checkmultiuser(username) VALUES ({0})", UsernameParm); } private void button1_Click(object sender, EventArgs e) { _cmd.Parameters[UsernameParm].Value = textBox1.Text; try { _cn.Open(); _cmd.ExecuteNonQuery(); } catch (Exception ex) // probably best to catch specific exceptions { // handle it } finally { _cn.Close(); } } } </code></pre> <p><strong>Just be sure to dispose of the connection and command objects (when the form closes or where ever makes the most sense for your application).</strong></p> <p>Using blocks are a safer alternative, but they will dispose of the object each time (although connections use connection pooling by default):</p> <pre><code>public partial class Form1 : Form { const string ConnString = "Enter your connection string here"; readonly string _insertQuery; const string UsernameParm = "@username"; public Form1() { InitializeComponent(); _insertQuery = String.Format("INSERT INTO checkmultiuser(username) VALUES ({0})", UsernameParm); } private void button1_Click(object sender, EventArgs e) { using (var cn = new SqlConnection(ConnString)) { using (var cmd = new SqlCommand(InsertQuery, cn)) { cmd.Parameters.Add(UsernameParm, SqlDbType.VarChar); cmd.Parameters[UsernameParm].Value = textBox1.Text; cn.Open(); cmd.ExecuteNonQuery(); } } } } </code></pre> <p>Any combination will work as well. You could setup the connection once and just wrap the command object in a using block. I know some people are not fans of nested using blocks (since behind the scenes it is try(try finally) finally)).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload