项目场景:
提示:快速迁移数据(将所查询数据快速插入新表中)
分析:
提示:数据库连接语句
public static string myConnStr = "server=172.0.0.1;database=Test;UID=IL;password='il'";
提示:数据库连接执行,返回DataSet方法
public static DataSet SQLStr(string mySQL)
{
SqlConnection myConn = new SqlConnection(myConnStr);
myConn.Open();
SqlDataAdapter myDa = new SqlDataAdapter(mySQL, myConn);
DataSet myDs = new DataSet();
myDa.Fill(myDs);
myDa.Dispose();
myDs.Dispose();
myConn.Dispose();
myConn.Close();
return myDs;
}
提示:数据库快速迁移方法
/// <summary>
/// sql数据快速迁移
/// </summary>
/// <param name="dt">查询DataTable结果</param>
/// <param name="table">目标table</param>
/// <param name="connectString">链接语句(server;database;UID;password)</param>
/// <param name="FieldNamedt">目标table列名</param>
/// <param name="FieldNamesql">目标table列名</param>
public static void DataTableToSQLServer(DataTable dt,string table, string connectString, string[] FieldNamedt, string[] FieldNamesql)
{
string connectionString = connectString;
using (SqlConnection destinationConnection = new SqlConnection(connectionString))
{
destinationConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
try
{
bulkCopy.DestinationTableName = table;//要插入的表的表名
bulkCopy.BatchSize = dt.Rows.Count;
int i = 0;
foreach (var s in FieldNamedt)
{
bulkCopy.ColumnMappings.Add(s, FieldNamesql[i]);//映射字段名 DataTable列名 ,数据库 对应的列名
i++;
}
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
提示:主函数
static void Main(string[] args)
{
string Now = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
string str = @"select ";
DataSet myds = SQLStr(str);
string[] FieldName = new string[] {"ID"
,"office"};
string table = "Analyse";
//查询结果字段和要导入表的字段名一致
DataTableToSQLServer(myds.Tables[0],table, DB_Str70, FieldName, FieldName);
//查询结果字段和要导入表的字段名不一致
//DataColumnCollection FieldNamedt = myds.Tables[0].Columns;
//DataTableToSQLServer(myds.Tables[0], table, myConnStr, FieldNamedt, FieldName);
}
解决方案:
提示:快速迁移数据