如何通过SQL存储过程在表中插入多个记录? [英] How to insert Multiple Records in a table through SQL Stored Procedure ?
问题描述
嗨!
我在我的项目中使用VB.NET 2010和SQL Server 2008.
我想将数据从DataGridView保存到SQL Server数据库表。
DataGridView包含多行数据,我想插入这些行在一个表中通过存储过程使用一个查询。
我只想将存储在网格中的数据传递给存储过程,然后存储过程将其插入到存储过程中使用INSERT查询所需的表。
任何人都可以帮助我吗?
谢谢!
DataTable dt = new DataTable();
// 创建具有所需结构的DataTable
dt.Columns.Add( Column1);
dt.Columns.Add( Column2);
foreach (GridViewRow row in GridView1.Rows)
{
// 查找gridview的控件全部添加值。
dt.Rows.Add(Column1,Column2);
}
如果(dt.Rows.Count > 0 )
{
string consString = ConfigurationManager.ConnectionStrings [ constr]。ConnectionString;
使用(SqlConnection con = new SqlConnection(consString))
{
使用(SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
// 设置数据库表名
sqlBulkCopy.DestinationTableName = TableName;
// [可选]:使用数据库表格映射DataTable列
sqlBulkCopy.ColumnMappings.Add( Column1, dbColumn1);
sqlBulkCopy.ColumnMappings.Add( Column2, dbColumn2);
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
更多信息
使用SqlBulkCopy将批量数据从GridView插入ASP.Net中的数据库 [ ^ ]
Hi !
I am using VB.NET 2010 and SQL Server 2008 in my project.
I want to save a data from a DataGridView to a table of SQL Server Database.
The DataGridView contains data in multiple rows and i want to insert these all rows in a table using one query through a stored procedure.
Simply i want to pass the data stored in grid to the stored procedure and then stored procedure will insert it in the required table using INSERT Query.
Can anyone help me ?
Thanks !
You should use sql bulk insert
DataTable dt = new DataTable(); //Create a DataTable with needed structure dt.Columns.Add("Column1"); dt.Columns.Add("Column2"); foreach (GridViewRow row in GridView1.Rows) { //Find controls of a gridview all add values. dt.Rows.Add(Column1,Column2); } if (dt.Rows.Count > 0) { string consString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(consString)) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) { //Set the database table name sqlBulkCopy.DestinationTableName = "TableName"; //[OPTIONAL]: Map the DataTable columns with that of the database table sqlBulkCopy.ColumnMappings.Add("Column1", "dbColumn1"); sqlBulkCopy.ColumnMappings.Add("Column2", "dbColumn2"); con.Open(); sqlBulkCopy.WriteToServer(dt); con.Close(); } } }
for more info
Using SqlBulkCopy to insert bulk data from GridView to database in ASP.Net[^]
这篇关于如何通过SQL存储过程在表中插入多个记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!