這是我做的在數據遷移方案從一個SQL Server的另一個或數據文件到SQL:
- 創建目標SQL Server上的新表(列名,主鍵等)
- 加載現有數據到一個DataTable(那你做了什麼的話)
- 現在查詢新表與DataAdapter的到另一個數據表(同你除了你現在查詢SQL表Excel文件一樣。)
- 從 '表' 加載到OLDDATA 'newtable的' 使用數據表法 「的load()」
string PathConn = (MYSQL Connection String goes here)
OleDbConnection conn = new OleDbConnection(PathConn);
conn.Open();
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + loadTextBox.Text + "$]", conn);
newTable = new DataTable();
myDataAdapter.Fill(newTable);
Now use the Load() Method on the new table:
newTable.Load(table.CreateDataReader(), <Specify LoadOption here>)
匹配的列將被導入的新數據表。 (您可以通過在選擇語句中使用別名來確保映射)
將現有數據加載到新表後,您將能夠使用DataAdapter將更改寫回數據庫。
示例數據寫回:CONNSTRING - 爲數據庫連接字符串, SelectStmt(可以使用相同的,你之前做了空表),並提供newtable的作爲dtToWrite
public static void writeDataTableToServer(string ConnString, string selectStmt, DataTable dtToWrite)
{
using (OdbcConnection odbcConn = new OdbcConnection(ConnString))
{
odbcConn.Open();
using (OdbcTransaction trans = odbcConn.BeginTransaction())
{
using (OdbcDataAdapter daTmp = new OdbcDataAdapter(selectStmt, ConnString))
{
using (OdbcCommandBuilder cb = new OdbcCommandBuilder(daTmp))
{
try
{
cb.ConflictOption = ConflictOption.OverwriteChanges;
daTmp.UpdateBatchSize = 5000;
daTmp.SelectCommand.Transaction = trans;
daTmp.SelectCommand.CommandTimeout = 120;
daTmp.InsertCommand = cb.GetInsertCommand();
daTmp.InsertCommand.Transaction = trans;
daTmp.InsertCommand.CommandTimeout = 120;
daTmp.UpdateCommand = cb.GetUpdateCommand();
daTmp.UpdateCommand.Transaction = trans;
daTmp.UpdateCommand.CommandTimeout = 120;
daTmp.DeleteCommand = cb.GetDeleteCommand();
daTmp.DeleteCommand.Transaction = trans;
daTmp.DeleteCommand.CommandTimeout = 120;
daTmp.Update(dtToWrite);
trans.Commit();
}
catch (OdbcException ex)
{
trans.Rollback();
throw ex;
}
}
}
}
odbcConn.Close();
}
}
希望這有助於。
newTable上的主鍵是必需的,否則你可能會得到一個CommandBuilder異常。
BR
Therak
你會發現這個有用的給據你已經得到作爲獲取數據到'DataTable':http://code.google.com/p/mysqlbulkcopy/ – dash
嘿,我有幾天前通過網站,但我不知道它是如何工作的,有什麼辦法可以爲我提供一些幫助? – user2837847