//上传
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "*jpg|*.JPG|*.gif|*.GIF|*.bmp|*.BMP|*.png|*.PNG";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string fullpath = openFileDialog1.FileName;//文件路径
this.txtfile.Text = fullpath;
try
{
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=(local); database =wanglei ; integrated security=true");
con.Open();
SqlCommand com = new SqlCommand("insert into imginfo values(@imgname )", con);
com.Parameters.Add("imgname", SqlDbType.Image);
com.Parameters["imgname"].Value = imagebytes;
int a = com.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("图片存入数据库成功!!!");
bind();
}
else
{
MessageBox.Show("图片存入数据库失败!!");
}
con.Close();
}
catch
{
MessageBox.Show("异常!!");
}
}
}
public void bind()
{
SqlConnection con = new SqlConnection("server=(local); database =wanglei ; integrated security=true");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from imginfo", con);
DataTable dt = new DataTable();
sda.Fill(dt);
this.dataGridView1.DataSource = dt;
}
//读取
private void button2_Click(object sender, EventArgs e)
{
byte[] imagebytes = null;
//打开数据库
SqlConnection con = new SqlConnection("server=(local); database =wanglei ; integrated security=true");
con.Open();
SqlCommand com = new SqlCommand("select top 1 * from imginfo", con);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
imagebytes = (byte[])dr.GetValue(1);
}
dr.Close();
com.Clone();
con.Close();
try
{
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pictureBox1.Image = bmpt;
}
catch
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//从数据库中读取、将图片显示在Picture控件上
byte[] b = new byte[0];
object objImg = dataGridView1.CurrentRow.Cells[1].Value;
b = (byte[])objImg;
if (b.Length > 0)
{
MemoryStream stream = new MemoryStream(b, true);
stream.Write(b, 0, b.Length);
pictureBox1.Image = Image.FromStream(stream);
stream.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
label2.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
string imid = label2.Text;
SqlConnection con = new SqlConnection("server=(local); database =wanglei ; integrated security=true");
con.Open();
SqlCommand com = new SqlCommand("delete from imginfo where imgid= '" + imid + "'", con);
int a = com.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("删除成功!!!");
bind();
}
else
{
MessageBox.Show("删失败!!");
}
}
}