How to insert BLOB datatype

送分小仙女□ 提交于 2019-12-18 08:51:26

问题


I'm using the following code to insert into a blob field:


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();

The insertion is ok but the image is not getting displayed while using "Open value in viewer":


回答1:


The binary data isn't being properly passed to your insert as you are using string concatenation - you'll get rawData.ToString() which probably just prints out the TypeName (hence your binary data being 13 bytes in length compared to the filesize of > 3000 bytes); try this instead:

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();

    }
}

I've introduced several concepts for you here; firstly, if you are going to load all of the binary data at once, simply use the static method File.ReadAllBytes - it's a lot less code.

Secondly, there is no need to use the fully qualified namespace each time - use the using directive

Thirdly, (slightly confusingly) there is a also a using statement in C#. This ensures that any object that implements IDisposable is properly cleaned up after itself. In the case of the connection, it will explicitly call Close and Dispose if you command succeeds or fails.

Finally, I've parameterized your query. Parameters are useful for many reasons; they help protect against SQL Injection, and, in this instance, they should also ensure that your data types are handled correctly. You can read more about SqlParameter (which, like, MySqlParameter is a database specific implementation but uses the same principles).

Tested as working with MySQL 5.5.15, MySQL Connector 5.2.7 running under .Net 4




回答2:


How about this:

It works fine for me.
Exepte I found out that it is the wrong one for me.

<?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";

// The table PRODUCTS with IMAGE. There are more data in that table. But i need only to update the IMAGE. The rest is already inserted.

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);
}
?>


来源:https://stackoverflow.com/questions/13208349/how-to-insert-blob-datatype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!