2012-11-03 164 views
4

我用下面的代碼插入到BLOB字段:在使用「打開如何插入BLOB數據類型


MySql.Data.MySqlClient.MySqlConnection conn; 
MySql.Data.MySqlClient.MySqlCommand cmd; 

conn = new MySql.Data.MySqlClient.MySqlConnection(); 
cmd = new MySql.Data.MySqlClient.MySqlCommand(); 

string SQL; 
int FileSize; 
byte[] rawData; 
FileStream fs; 

conn.ConnectionString = "server=192.168.1.104;uid=root;" + 
     "pwd=root;database=cady234;"; 

fs = new FileStream(@"d:\Untitled.gif", FileMode.Open, FileAccess.Read); 
FileSize = (int)fs.Length; 

rawData = new byte[FileSize]; 
fs.Read(rawData, 0, FileSize); 
fs.Close(); 

conn.Open(); 

string strFileName = "test name"; 
SQL = "INSERT INTO file (file_name, file_size, file) VALUES ('" + strFileName + "', "+FileSize+", '"+rawData+"')"; 

cmd.Connection = conn; 
cmd.CommandText = SQL; 

cmd.ExecuteNonQuery(); 
conn.Close(); 

插入正常,但沒有得到顯示的圖像在查看器「值:

enter image description here

回答

12

二進制數據沒有被正確地傳遞給你的插入物你會得到rawData.ToString()這可能只是打印出TypeName(因此你的二進制數據的長度是13個字節,而文件大小大於3000字節)。試試這個:

byte[] rawData = File.ReadAllBytes(@"d:\Untitled.gif"); 
FileInfo info = new FileInfo(@"d:\Untitled.gif"); 

int fileSize = Convert.ToInt32(info.Length); 

using(MySqlConnection connection = new MySqlConnection("server=192.168.1.104;uid=root;pwd=root;database=cady234;")) 
{ 
    using(MySqlCommand command = new MySqlCommand()) 
    { 
     command.Connection = connection; 
     command.CommandText = "INSERT INTO file (file_name, file_size, file) VALUES (?fileName, ?fileSize, ?rawData);"; 
     MySqlParameter fileNameParameter = new MySqlParameter("?fileName", MySqlDbType.VarChar, 256); 
     MySqlParameter fileSizeParameter = new MySqlParameter("?fileSize", MySqlDbType.Int32, 11); 
     MySqlParameter fileContentParameter = new MySqlParameter("?rawData", MySqlDbType.Blob, rawData.Length); 

     fileNameParameter.Value = "test name"; 
     fileSizeParameter.Value = fileSize; 
     fileContentParameter.Value = rawData; 

     command.Parameters.Add(fileNameParameter); 
     command.Parameters.Add(fileSizeParameter); 
     command.Parameters.Add(fileContentParameter); 

     connection.Open(); 

     command.ExecuteNonQuery(); 

    } 
} 

我在這裏介紹了幾個概念;首先,如果要一次加載所有二進制數據,只需使用靜態方法File.ReadAllBytes - 代碼少得多。

其次,沒有必要每次都使用完全合格的命名空間 - 使用using directive

第三,(略容易混淆)有在C#中也using statement。這可以確保實現IDisposable的任何對象都可以在其自身之後正確清理。在連接的情況下,如果命令成功或失敗,它將顯式調用Close和Dispose。

最後,我參數化了您的查詢。參數很有用,原因很多;它們有助於防範SQL Injection,在這種情況下,它們還應確保您的數據類型得到正確處理。你可以閱讀更多關於SqlParameter(其中,像MySqlParameter是一個數據庫特定的實現,但使用相同的原則)。

進行試驗與MySQL 5.5.15工作,MySQL連接5.2.7 .NET 4中

+0

謝謝! 我試過但得到這個異常: {「你的SQL語法有錯誤;在第1行檢查與你的MySQL服務器版本對應的正確語法對應的手冊 - '_fileSize,_rawData') 「} 我正在使用MySQL版本5 – Jobi

+1

請嘗試使用下面的sql代替:請將command.CommandText =」INSERT INTO file(file_name,file_size,file)VALUES(?,?,?)「;我將有機會在稍後進行測試。 – dash

+0

現在得到另一個異常: {「Parameter'?'必須定義。「} – Jobi

-2

這個怎麼樣下運行:

它工作正常的我。
Exepte我發現它對我來說是錯誤的。

<?php 
// csv invoeren naar pos. 

$CSV = "uitvoer.csv"; 
// The CSV file has only 2 colums; The "Reference" and the image name (in my case the barcode with "thumb_" in front of it. 

$username = "Username"; 
$password = "Passwwoorrdd"; 
$database = "POS"; 
$counter = 0; 

// Create connection 
$conn = new mysqli("localhost", $username, $password, $database); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully <br>"; 

//$mysqli->select_db(); 
ini_set('max_execution_time', 1000); //300 seconds = 5 minutes 

if (($handle = fopen($CSV, "r")) !== FALSE) { 
    while (($data = fgetcsv($handle, 1050, ",")) !== FALSE) { 
     // this loops through each line of your csv, putting the values into array elements 

    $counter++; 

$IDEE = $data[0]; 
     // It seems that after opening the image the $data is mixed up. 

$imag = "photos/".$data[1]; // where "photos/' the folder is where this php file gets executed (mostly in /var/www/ of /var/www/html/) 

$fh = fopen($imag, "r"); 
$data = addslashes(fread($fh, filesize($imag))); 
fclose($fh); 

echo " Ref: ".$IDEE." ----".$counter."----<br>"; 
    // If there will be a time-out. You could erase the part what is already done minus 1. 
$sql = "UPDATE PRODUCTS SET IMAGE='".$data."' WHERE CODE=$IDEE"; 

//該錶帶有圖像的產品。該表中有更多數據。但我只需要更新圖像。其餘的已經插入。

if ($conn->query($sql) === TRUE) { 
    echo "Tabel <b>products</b> updated successfully<br>"; 
} else { 
    echo "<br>Error updating tabel <b>Products</b>: " . $conn->error; 
Exit(); 
} 
    } 
    fclose($handle); 
} 
?> 
+0

這是在PHP中...雖然是一種創新的方法,但OP的代碼是用C#編寫的。他們需要安裝PHP解釋器才能使用此代碼。 – vapcguy