using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";//打开的文件格式
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName;//文件路径
FileStream fs = new FileStream(fullpath, FileMode.Open);//创建读写文件对象
byte[] imagebytes = new byte[fs.Length];//
BinaryReader br = new BinaryReader(fs);//将文件转换成二进制
imagebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
//打开数据库
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;database=picDB");
con.Open();
SqlCommand com = new SqlCommand("insert into picTb values(@pic)", con);
com.Parameters.Add("pic", SqlDbType.Image);
com.Parameters["pic"].Value = imagebytes;
com.ExecuteNonQuery();
con.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=;database=picDB");
string str = "select top 1 pic from pictb";
try
{
SqlCommand command = new SqlCommand(str, con);
con.Open();
SqlDataReader picture = command.ExecuteReader();
if (picture.Read())
{
MessageBox.Show(picture.GetValue(0).ToString());
MemoryStream ms = new MemoryStream((byte[])picture.GetValue(0));
pictureBox1.Image = Image.FromStream(ms);
picture.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("错误");
}
finally
{
con.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}