开始想直接在sql server 2008用存储过程写。用到了OpenRowSet、opendatasource两个函数,然而启用Ad Hoc DistributedQueries的方法后还是一直报错,查了资料可能是因为使用的是64位系统,最终也没改好,以后再来研究,可以参考http://www.cnblogs.com/OpenCoder/archive/2010/03/18/1689321.html
由于时间紧迫,就换了个方法在vs2014上用c#做:
A 打开Access数据库
private bool OpenDbAccess()
{
try
{
//捕获数据库打开异常
OleDbConnection _oleDbConn = new OleDbConnection(@"provider=microsoft.jet.oledb.4.0; Data Source=C:\Data.mdb");
_oleDbConn.Open();
return true;
}
catch (Exception)
{
return false;
}
}
B 打开sql server数据库
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=服务器地址;uid=sa;pwd=xxx;database=数据库名";
conn.Open();
C 用SQL语句查询Access表内容
OleDbDataAdapter _oleDbAda = new OleDbDataAdapter(SQL语句, Access表连接);
if (!string.IsNullOrEmpty(SQL语句) && !string.IsNullOrEmpty(Access表名))//要求表和sql语句不为空
{
var dt = new DataSet();//声明结果集对象
_oleDbAda.Fill(dt, tableName);
if (dt != null)
{
SqlBulkCopyData(dt);
}
_oleDbAda.Dispose();
_oleDbConn.Close();
return dt;
}
else
{
return null;
}
DataSet的Fill方法形象的解说 http://blog.sina.com.cn/s/blog_67737c1d01017ike.html
D 对Access表中数据进行修改
方法:克隆Access表结构,修改后存入新表中if (dt != null)
{
//将DataSet转成DataTable
DataTable data = dt.Tables[0];
//克隆data表用于修改Access内容
DataTable dtResult = new DataTable();
dtResult = data.Clone();//克隆表结构
foreach (DataRow row in data.Rows)
{
DataRow rowNew = dtResult.NewRow();
rowNew["ID"] = row["ID"];
//修改Area记录值,保留到省
if (rowNew["Area "] != null)
{
var areaInt = row["Area"].ToString().IndexOf(" ");
rowNew["Area "] = row["Area "].ToString().Substring(0, areaInt); //截取字符串空格前面的内容
}
else
{
rowNew["Area "] = row["Area "];
}
//修改Type记录值,去掉“中国”
if (rowNew["Type"] != null)
{
rowNew["Type "] = row["Type "].ToString().Replace("中国", " ");
}
else
{
rowNew["Type "] = row["Type "];
}
dtResult.Rows.Add(rowNew);
Access转SQL server 注意事项 http://www.jb51.net/article/6869.htm
E Access表中内容批量复制到Sqlserver 中
SqlTransaction sqlbulkTransaction = conn.BeginTransaction();
//插入数据的同时检查约束,如果发生错误调用sqlbulkTransaction事务
SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.CheckConstraints, sqlbulkTransaction);
//直接导入大数据
for (var i = 0; i < 6; i++)//i为Access中列的数量
{
copy.ColumnMappings.Add(dtResult.Columns[i].ColumnName, data.Columns[i].ColumnName);
}
try
{
copy.WriteToServer(dtResult);
//提交事务
sqlbulkTransaction.Commit();
}
catch (Exception e)
{
//回滚事务
sqlbulkTransaction.Rollback();
Console.WriteLine(e.ToString());
}
finally
{
copy.Close();
conn.Close();
}
参考:
C#操作连接Access数据库
http://jingyan.baidu.com/article/ab0b563094fab9c15afa7d8c.html
关于批量导入数据类SqlBulkCopy导入数据时增加额外的列
修改数据表DataTable某一列的类型和记录值http://www.cnblogs.com/starxp/articles/1789607.html
批量复制操作(SqlBulkCopy)的出错处理:事务提交、回滚
http://blog.csdn.net/westsource/article/details/6658109
http://www.cnblogs.com/zfanlong1314/archive/2013/02/05/2892998.html
http://www.cnblogs.com/scottckt/archive/2011/02/16/1955862.html
http://blog.csdn.net/okman1214/article/details/6938037