原文: http://aspalliance.com/articleViewer.aspx?aId=477&pId=-1
作者:Andrew Mooney 翻譯:孟子E章 [下載原始碼
// 檢查表是否存在,如果存在DataTable中將有一筆記錄
if(schemaTable.Rows.Count < 1)
sqlCmd = "create table " + tableName + " (";
for(int i = 0;i < dataTableXml.Columns.Count;i++)
{
// 新增列text/string type 長度100
sqlCmd = sqlCmd + dataTableXml.Columns[i].ColumnName.ToString() + " char(100),";
}
sqlCmd = sqlCmd .Substring(0,sqlCmd.Length - 1) + ");";
OleDbCommand oledbCmd = new OleDbCommand(sqlCmd,oledbConn);
oledbCmd.ExecuteNonQuery();
新增XML資料到資料庫
// 遍歷DataTable中的Rows
foreach(DataRow dr in dataTableXml.Rows)
{
string sqlCmd = "insert into [" + tableName + "] (";
// 遍歷Datatable的列
for(int i = 0;i < dataTableXml.Columns.Count;i++)
{
// 新增column name
sqlCmd = sqlCmd + dataTableXml.Columns[i].ColumnName.ToString() + ",";
}
sqlCmd = sqlCmd.Substring(0,sqlCmd.Length - 1) + ") values (";
// 遍歷DataTable columns
for(int x = 0;x < dataTableXml.Columns.Count;x++)
{
// 新增column value到row
sqlCmd = sqlCmd + "'" + dr[x].ToString().Replace("'","''") + "',";
}
sqlCmd = sqlCmd.Substring(0,sqlCmd.Length - 1) + ");";
OleDbCommand oledbCmd = new OleDbCommand(sqlCmd,oledbConn);
oledbCmd.ExecuteNonQuery();
}
注意的問題:
測試時先下載原始碼,建立一個空的資料庫,設定可修改權限Database.mdb,Database.xls,為FoxPro/dBase 建立一個空目錄
連接字串範例:
Access: Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:datadatabase.mdb;
Excel: Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:datadatabase.xls;Extended Properties=Excel 8.0;
FoxPro/dBase: Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:data;Extended Properties=dBASE IV;
SQL Server: Provider=SQLOLEDB; Data Source=localhost; Initial Catalog=database;User ID=sa;Password=;