我有两个几乎相同的数据库(都是* .mdb),但其中一个有很少的新表。现在,我只能使用以下代码检测应导入的表:
public static List<string> GetDBTables(string path)
{
List<string> allTables = new List<string>();
String connect = ("Provider=Microsoft.JET.OLEDB.4.0;data source="
+ path + ";Persist Security Info=False;");
OleDbConnection con = new OleDbConnection(connect);
con.Open();
DataTable tables = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] { null, null, null, "TABLE" });
int counter = 1;
foreach (DataRow row in tables.Rows)
{
allTables.Add(row[2].ToString());
counter++;
}
con.Close();
return allTables;
}
var withNewTables = GetDBTables(".\\one.mdb");
var withoutNewTables = GetDBTables(".\\another.mdb");
var NotFoundTables = withNewTables.Except(withoutNewTables).ToList();
如何使用C#在旧数据库中导入这些表?
答案 0 :(得分:6)
Access SQL提供了两个在这里很有用的功能。
SELECT <field list> INTO NewTable
FROM table_name IN 'path to other db file'
所以我可以从OleDb连接到我的目标db文件执行此语句,它将从其他db文件中 tblFoo 中包含的数据创建 tblFoo_copy , NewData.mdb
SELECT f.* INTO tblFoo_copy
FROM tblFoo AS f IN 'C:\Users\hans\Documents\NewData.mdb';
为要导入的每个表构建并执行类似的语句。
答案 1 :(得分:3)
好吧,除了HansUp的回答,我在C#上发布了这个实现:
public static void insertTables(string path_from, string path_to,
List<string> _tables)
{
string conString = ("Provider=Microsoft.JET.OLEDB.4.0;data source="
+ path_to + ";Persist Security Info=False;");
OleDbConnection dbconn = new OleDbConnection(conString);
dbconn.Open();
OleDbCommand dbcommand = new OleDbCommand();
_tables.ForEach(delegate(String name)
{
string selQuery = "SELECT f.* INTO " + name + " FROM " + name
+ " AS f IN '" + path_from + "';";
dbcommand.CommandText = selQuery;
dbcommand.CommandType = CommandType.Text;
dbcommand.Connection = dbconn;
int result = dbcommand.ExecuteNonQuery();
});
dbconn.Close();
}
insertTables(".\\one.mdb", ".\\another.mdb", NotFoundTables);