public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.pictureBox1.ImageLocation))
{
MessageBox.Show("請選擇要插入的圖片!");
return;
}
using (SqlConnection cn = new SqlConnection("Server=.;UID=sa;Pwd=sa;Database=cspro"))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO image_table(pic) VALUES (@pic)", cn))
{
cmd.Parameters.Add("@pic", SqlDbType.Image).Value = File.ReadAllBytes(this.pictureBox1.ImageLocation);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("圖片插入成功!");
}
}
}
private void button3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Title = "請選擇要插入的圖片";
ofd.Filter = "Gif圖片|*.gif|Jpg圖片|*.jpg|BMP圖片|*.bmp";
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.Multiselect = false;
if (ofd.ShowDialog(this) == DialogResult.OK)
{
this.pictureBox1.ImageLocation = ofd.FileName;
}
else
{
MessageBox.Show("你沒有選擇圖片");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
//隨機顯示一張圖片
using (SqlConnection cn = new SqlConnection("Server=.;UID=sa;Pwd=sa;Database=cspro"))
{
using (SqlCommand cmd = new SqlCommand("SELECT pic FROM image_table ORDER BY RAND()", cn))
{
cn.Open();
this.pictureBox1.Image = Image.FromStream(new MemoryStream((byte[])cmd.ExecuteScalar(), false));
cn.Close();
}
}
}
}
如圖