2014-09-12 112 views
0

我正在開發一個應用程序以在C#中的兩個數據庫之間傳輸數據。我有一種在MySQL中插入BLOB類型數據的方法。當執行它我收到錯誤Unable to cast object of type 'System.Byte[]' to type 'System.IConvertible'.錯誤 - 無法投射'System.Byte []'類型的對象來鍵入'System.IConvertible'

編號#

public static void FiletoSql(MemoryStream fileToPut, MySqlConnection con) 
    { 
     try 
     { 
     const string preparedCommand = 
     @"update user_account_statement set [email protected], [email protected] where statement_Id=1070"; 
     using (var sqlWrite = new MySqlCommand(preparedCommand, con)) 
     { 
     sqlWrite.Parameters.AddWithValue("@ssfile", MySqlDbType.Blob).Value = fileToPut.ToArray(); 
     sqlWrite.Parameters.AddWithValue("@udatetime", MySqlDbType.DateTime).Value = 
     DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); 
     sqlWrite.ExecuteNonQuery(); 
     } 
     } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
    } 

我沒有得到什麼的轉換是問題。

編輯:我已經試過這樣:

var fileData=new MySqlParameter("@ssfile",MySqlDbType.Blob,data.Length) { 
    Value = data 
}; 
sqlWrite.Parameters.Add(fileData); 
sqlWrite.Parameters.AddWithValue("@udatetime", MySqlDbType.DateTime) 
        .Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); 
var cmd = sqlWrite; 
sqlWrite.ExecuteNonQuery(); 

,現在我得到錯誤輸入字符串的不正確的格式。

+0

聽起來像是你將不得不實現接口? – Noctis 2014-09-12 11:11:18

+0

@Noctis不,它只是一種將數據插入MySQL表的方法。 – 2014-09-12 11:13:44

+0

看起來你看起來像這樣http://stackoverflow.com/a/13208599/1328536 – fuchs777 2014-09-12 11:25:00

回答

0

哇!得到了答案。

測試的解決方案:

public static void FiletoSql(MemoryStream fileToPut, MySqlConnection con) 
    { 
     byte[] data = fileToPut.ToArray(); 
     try 
     { 
      const string preparedCommand = 
       @"update user_account_statement set [email protected], [email protected] where statement_Id=1070"; 

      using (var sqlWrite = new MySqlCommand(preparedCommand, con)) 
      { 
       sqlWrite.Parameters.Add("@ssfile", MySqlDbType.Blob); 
       sqlWrite.Parameters.Add("udatetime", MySqlDbType.DateTime); 

       sqlWrite.Parameters["@ssfile"].Value = data; 
       sqlWrite.Parameters["udatetime"].Value=DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); 
       sqlWrite.ExecuteNonQuery(); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 
+0

@Noctis讚賞你的指導。 :) – 2014-09-13 13:17:33

+0

@ fuchs777你的指導表示讚賞。 – 2014-09-13 13:18:32