1. 程式人生 > >轉載:C#向VFP資料庫中插入Numeric型的值

轉載:C#向VFP資料庫中插入Numeric型的值

最近做一個C#程式,實現將SQLServer中的資料匯入到Visual Foxpro 6.0的.dbf資料檔案中。更新Numeric型別欄位的值時出現錯誤:

System.Data.Odbc.OdbcException:ERROR [22018] [Microsoft][ODBC Visual FoxPro Driver]Data type mismatch.

原程式類似如下:

//------------------------------------------------------------------------

//到.dbf資料庫檔案的ODBC連線字串
string strOdbcConn = @" DRIVER=Microsoft Visual FoxProDriver;UID=;Collate=Machine;BackgroundFetch=Yes;   Exclusive=No;SourceType=DBF;SourceDB="+ strFilePath +";";
//獲取DataTable
string strSQL = "Select * From table1 ;
DataSet dataSet = new DataSet(); 
OdbcDataAdapter odbcDA = new OdbcDataAdapter(strSQL,strOdbcConn);
odbcDA.Fill(dataSet,"table1");
DataTable table = dataSet.Tables["table1"];
//向DataTable中新增記錄  
DataRow row = table.NewRow();
row["DateFrom"] = Convert.ToDateTime("2005-09-10");//日期型欄位
row["Num"]   = Convert.ToDecimal(10);//Numric(16,0)型欄位
table.Rows.Add(row);
//更新到資料庫中
OdbcCommandBuilder builder = new OdbcCommandBuilder(odbcDA);
odbcDA.InsertCommand = builder.GetInsertCommand();
odbcDA.Update(dataSet,"table1");

//----------------------------------------------------------------

程式執行時,在對row["Num"]賦值時並不出錯,執行到oodbcDA.Update(dataSet,"table1");時出錯,根源就在於

對row["Num"]的賦值,實在找不到好的解決辦法。

後來,用SQL語句測試,如:update table1 set Num=10;執行正確,就想用SQL語句insert解決,經測試可行。

SQL-Insert語句如下:

Insert Into table1(DateFrom, Num) Values({^2005-09-10},10)

程式相應的改成如下的了:

//------------------------------------------------------------------

string strOdbcConn = @" DRIVER=Microsoft Visual FoxProDriver;UID=;Collate=Machine;BackgroundFetch=Yes;   Exclusive=No;SourceType=DBF;SourceDB="+ strFilePath +";";
OdbcConnection odbcConn = new OdbcConnection(strOdbcConn);
string sqlInsert = "Insert Into table1(DateFrom, Num) Values({^2005-09-10},10)";
OdbcCommand odbcComm = new OdbcCommand(sqlInsert,odbcConn);
odbcComm.Connection.Open();
odbcComm.ExecuteNonQuery();
odbcConn.Close();

//----------------------------------------------------------------