|
■No55364 (魔界の仮面弁士) に追記
#region ヘルパーメソッド
static string Dump(string targetFile) {
byte[] binImg = File.ReadAllBytes(targetFile);
return BitConverter.ToString(binImg).Replace("-", "");
}
static Image LoadImage(byte[] bin) {
using (MemoryStream stm = new MemoryStream(bin))
{
return Image.FromStream(stm);
}
}
#endregion
OleDbConnection cn = new OleDbConnection(@"
Provider=Microsoft.JET.OLEDB.4.0;
Data Source=C:\db1.mdb;
");
/// <summary>デモ用テーブルの作成</summary>
private void button1_Click(object sender, EventArgs e) {
cn.Open();
OleDbCommand cmd = cn.CreateCommand();
cmd.CommandText = @"
CREATE TABLE TestTable (
ID AUTOINCREMENT(10000, 10) PRIMARY KEY,
IMG1 OLEOBJECT NULL,
IMG2 OLEOBJECT NULL
);
";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("テーブル作成");
}
/// <summary>SQLにデータを埋め込む</summary>
private void button2_Click(object sender, EventArgs e) {
cn.Open();
OleDbCommand cmdINSERT = cn.CreateCommand();
cmdINSERT.CommandText = @"
INSERT INTO TestTable (IMG1, IMG2) VALUES (
0x" + Dump(@"C:\Windows\珈琲カップ.bmp") + @"
,0x" + Dump(@"C:\Windows\シャボン.bmp") + @"
);
";
cmdINSERT.ExecuteNonQuery();
cn.Close();
MessageBox.Show("SQLにバイナリを埋め込み");
}
/// <summary>パラメータクエリ</summary>
private void button3_Click(object sender, EventArgs e) {
cn.Open();
OleDbCommand cmdINSERT = cn.CreateCommand();
cmdINSERT.CommandText = @"
PARAMETERS P1 OLEOBJECT, P2 OLEOBJECT;
INSERT INTO TestTable (IMG1, IMG2)
VALUES ( P1, P2 );
";
OleDbParameter P1 = new OleDbParameter("P1", DbType.Object);
OleDbParameter P2 = new OleDbParameter("P2", DbType.Object);
cmdINSERT.Parameters.Add(P1);
cmdINSERT.Parameters.Add(P2);
P1.Value = File.ReadAllBytes(@"C:\WINDOWS\羽毛.bmp");
P2.Value = File.ReadAllBytes(@"C:\WINDOWS\大草原の風.bmp");
cmdINSERT.ExecuteNonQuery();
cn.Close();
MessageBox.Show("パラメータクエリでバイナリを渡す");
}
/// <summary>画像読み込み</summary>
private void button4_Click(object sender, EventArgs e) {
cn.Open();
OleDbCommand cmdSELECT = cn.CreateCommand();
cmdSELECT.CommandText = @"
SELECT TOP 1
ID, IMG1, IMG2
FROM
TestTable
ORDER BY
ID DESC
";
OleDbDataReader reader = cmdSELECT.ExecuteReader();
if (reader.Read()) {
pictureBox1.Image = LoadImage((byte[])reader.GetValue(1));
pictureBox2.Image = LoadImage((byte[])reader.GetValue(2));
MessageBox.Show("ID=" + reader.GetInt32(0));
}
cn.Close();
MessageBox.Show("最後に追加された画像の読み取り");
}
|