How do I translate a List into a SqlParameter for a Sql In statement? [duplicate]

You could try something like this: string sql = “SELECT dscr FROM system_settings WHERE setting IN ({0})”; string[] paramArray = settingList.Select((x, i) => “@settings” + i).ToArray(); cmd.CommandText = string.Format(sql, string.Join(“,”, paramArray)); for (int i = 0; i < settingList.Count; ++i) { cmd.Parameters.Add(new SqlParameter(“@settings” + i, settingList[i])); }

Is SqlCommand.Dispose() required if associated SqlConnection will be disposed?

Just do this: using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[“MyConn”].ConnectionString)) using(var command = connection.CreateCommand()) { command.CommandText = “…”; connection.Open(); command.ExecuteNonQuery(); } Not calling dispose on the command won’t do anything too bad. However, calling Dispose on it will suppress the call to the finalizer, making calling dispose a performance enhancement.

When should “SqlDbType” and “size” be used when adding SqlCommand Parameters?

In my experience, I would make sure I do these things: make sure it’s you that defines the data type for the parameter. ADO.NET does a decent job at guessing, but in some cases, it can be terribly off – so I would avoid this method: cmd.Parameters.Add(“@Name”).Value = “Bob”; cmd.Parameters.AddWithValue(“@Name”, “Bob”); Letting ADO.NET guess the … Read more

ReadOnlyException DataTable DataRow “Column X is read only.”

using DataAdapter.Fill does not load the database schema, which includes whether a column is a primary key or not, and whether a column is read-only or not. To load the database schema, use DataAdapter.FillSchema, but then that’s not your questions. using DataReader to fill a table loads the schema. So, the index column is read-only … Read more

How to run multiple SQL commands in a single SQL connection?

Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection. // Create the first command and execute var command = new SqlCommand(“<SQL Command>”, myConnection); var reader = command.ExecuteReader(); // Change the SQL Command and execute command.CommandText = “<New SQL Command>”; command.ExecuteNonQuery();