I want to insert a list of objects into sql server table. However, currently, I have to open and close the sql connection each time I insert a record row.
I just wonder if there is a way I can insert all the objects in the record list at one time? Here is the code snippet.
public void InsertDataToDb()
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
var records = GetRecords();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd =
new SqlCommand(
"INSERT INTO TableName (param1, param2, param3) VALUES (@param1, @param2, @param3)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
foreach (var item in records)
{
cmd.Parameters.AddWithValue("@param1", item.param1);
cmd.Parameters.AddWithValue("@param2", item.param2);
cmd.Parameters.AddWithValue("@param3", item.param3);
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
conn.Close();
}
}
}
To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.
You can create lists of SQL Query or Fixed Data values . In the Data Model components pane, click List of Values and then click Create new List of Values. Enter a Name for the list and select a Type.
CREATE FUNCTION dbo. SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>'). query('.
To quickly generate an insert statement in SQL Server Management Studio for a table that already exists, right click the table, navigate to Script Table as > INSERT To > New Query Editor Window.
I'm making assumptions about your datatypes (change them as you need, based on what the actual DbTypes are), but something like this should do it:
public void InsertDataToDb()
{
string connectionString = ConfigurationManager.ConnectionStrings["connection"].
ConnectionString;
var records = GetRecords();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd =
new SqlCommand(
"INSERT INTO TableName (param1, param2, param3) " +
" VALUES (@param1, @param2, @param3)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.Add("@param1", DbType.String);
cmd.Parameters.Add("@param2", DbType.String);
cmd.Parameters.Add("@param3", DbType.String);
foreach (var item in records)
{
cmd.Parameters[0].Value = item.param1;
cmd.Parameters[1].Value = item.param2;
cmd.Parameters[2].Value = item.param3;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
I'd also recommend invoking a transaction so that all 100 inserts can be done as a single transaction.
-- EDIT --
Regarding the transaction, here is about how you would add it:
conn.Open(); // already there -- to show you where to start the transaction
SqlTransaction trans = conn.BeginTransaction();
string sql = "INSERT INTO TableName (param1, param2, param3) " +
"VALUES (@param1, @param2, @param3)";
SqlCommand cmd = new SqlCommand(sql, conn, trans);
And then, before you close your connection (or after the last statement in the transaction, which can include selects, updates, whatever):
trans.Commit();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With