using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApp19
{
/*
--表结构创建
IF OBJECT_ID('t') IS NOT NULL
DROP TABLE t
GO
CREATE TABLE t(
id INT PRIMARY KEY,
[name] NVARCHAR(20) NOT NULL
)
GO
*/
class Program
{
static void Main(string[] args)
{
//连接串,自行修改
string connString = "data source=(local);initial catalog=test;Integrated Security=True";
//1. 得到一个空表结构
string sql = "select * from t where 1=0";
DataTable dt = null;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
}
//2. 添加数据
for (int i = 1; i <= 10; i++) {
DataRow dr = dt.NewRow();
dr["id"] = i;
dr["name"] = "n" + i.ToString();
dt.Rows.Add(dr);
}
//3. 插入到目标表
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
bulkCopy.DestinationTableName = "t"; //目标表名
bulkCopy.WriteToServer(dt); //将 DataTable 写入到目标表
}
}
Console.Read();
}
}//end of class
}//end of namespaces