当前位置:Gxlcms >
数据库问题 >
创建ACCESS数据库,并且创建表和数据。重点:关闭ACCESS数据库引用
创建ACCESS数据库,并且创建表和数据。重点:关闭ACCESS数据库引用
时间:2021-07-01 10:21:17
帮助过:1人阅读
<summary>
/// 创建ACCESS数据库,并且创建表和数据
/// </summary>
/// <param name="dictTable"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public int DataTableToAccess(Dictionary<
string, DataTable> dictTable,
string filePath)
{
int count =
0;
string connStr =
string.Format(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5", filePath);
try
{
ADOX.Catalog catalog =
new ADOX.Catalog();
catalog.Create(connStr); //创建ACCESS数据库
ADODB.Connection cn =
new ADODB.Connection();
cn.Open(connStr, null,
null, -
1);
catalog.ActiveConnection =
cn;
foreach (
var item
in dictTable)
{
ADOX.Table table =
new ADOX.Table();
table.Name =
item.Key;
foreach (DataColumn c
in item.Value.Columns)
{
table.Columns.Append(c.ColumnName, DataTypeEnum.adLongVarWChar);
}
catalog.Tables.Append(table);
}
#region 释放COM引用的对象 【该代码块在Release模式下运行有效】
System.Runtime.InteropServices.Marshal.ReleaseComObject(catalog);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(catalog);
catalog =
null;
cn.Close();
GC.WaitForPendingFinalizers();
GC.Collect();
#endregion
}
catch (Exception ex)
{
throw ex;
}
foreach (
var item
in dictTable)
{
StringBuilder sbColumns =
new StringBuilder();
StringBuilder sbValues =
new StringBuilder();
sbColumns.Append("insert into [" + item.Key +
"](");
foreach (DataColumn c
in item.Value.Columns)
{
sbColumns.Append("[" + c.ColumnName +
"],");
}
sbColumns.Remove(sbColumns.Length -
1,
1);
sbColumns.Append(")");
foreach (DataRow row
in item.Value.Rows)
{
sbValues.Append(sbColumns.ToString());
sbValues.Append("values( ");
foreach (DataColumn c
in item.Value.Columns)
{
sbValues.Append("‘" + CommUtils.DtRowFilter(row[c.ColumnName] +
"") +
"‘,");
}
sbValues.Remove(sbValues.Length -
1,
1);
sbValues.Append(");");
sbValues.AppendLine("");
//using (DBHelperAccess access = new DBHelperAccess(connStr))
//{
DBHelperAccess access =
new DBHelperAccess(connStr);
//DBHelperAccess access = new DBHelperAccess(connStr);
access.ExecuteSQLNonquery(sbValues.ToString());
access.Conn.Dispose();
access =
null;
//}
sbValues.Clear();
}
GC.Collect();
}
return count;
}
创建ACCESS数据库,并且创建表和数据。重点:关闭ACCESS数据库引用
标签: