5

次のコードを使用して、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();

挿入は問題ありませんが、「ビューアで値を開く」を使用している間、画像が表示されません:

ここに画像の説明を入力

4

2 に答える 2

17

文字列連結を使用しているため、バイナリデータがインサートに適切に渡されていませんrawData.ToString()。おそらくTypeNameを出力するだけです(したがって、バイナリデータの長さはファイルサイズが3000バイトを超えるのに対し、13バイトです)。代わりにこれを試してください:

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ディレクティブを使用してください

第三に、(少し紛らわしいことに)C#にもusingステートメントがあります。これにより、IDisposableを実装するすべてのオブジェクトがそれ自体の後で適切にクリーンアップされます。接続の場合、コマンドが成功または失敗すると、明示的にCloseandDisposeを呼び出します。

最後に、クエリをパラメータ化しました。パラメータは多くの理由で役立ちます。これらはSQLインジェクションからの保護に役立ち、この場合、データ型が正しく処理されることも保証する必要があります。SqlParameterの詳細を読むことができます(MySqlParameterはデータベース固有の実装ですが、同じ原則を使用します)。

.Net4で実行されているMySQL5.5.15、MySQLConnector5.2.7で動作することをテストしました

于 2012-11-03T11:11:28.940 に答える
-4

これはどう:

それは私にとってはうまくいきます。
私はそれが私にとって間違っていることに気づきました。

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

// IMAGE を含むテーブル PRODUCTS. そのテーブルにはさらにデータがあります。しかし、私は IMAGE を更新するだけで済みます。残りはすでに挿入されています。

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);
}
?>
于 2016-04-27T13:48:07.353 に答える