数据库字段
界面结构
C#代码
存入数据库
string connString = "initial catalog=Picture;Server=(local);user id=molihuan;password=123456";//数据库连接字符串
private void cun_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "*jpg|*.JPG|*.GIF|*.GIF|*.BMP|*.BMP";
try{
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
string picturePath = openFileDialog1.FileName; //选择的图片路径
SqlConnection connection = new SqlConnection(connString);//创建connection对象
string sql = "insert into Images (ID,Data) values ("+textBox2.Text+",@blobdata)";
SqlCommand command = new SqlCommand(sql, connection);
//创建FileStream对象
FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
//声明Byte数组
Byte[] mybyte = new byte[fs.Length];
//读取数据
fs.Read(mybyte, 0, mybyte.Length);
fs.Close();
//转换成二进制数据,并保存到数据库
SqlParameter prm = new SqlParameter
("@blobdata", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
command.Parameters.Add(prm);
//打开数据库连接
connection.Open();
command.ExecuteNonQuery();//执行代码
connection.Close();
MessageBox.Show("存入数据库成功");
}
}catch (Exception ex){MessageBox.Show(ex.Message);}
}
读取数据库存储的图片
private void du_Click(object sender, EventArgs e)
{
byte[] imagebytes = null;
//打开数据库
SqlConnection con = new SqlConnection(connString);
con.Open();
if (textBox1.Text.Equals(""))
{
textBox1.Text = "1";
}
SqlCommand com = new SqlCommand("select * from Images where ID="+textBox2.Text, con);
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
imagebytes = (byte[])dr.GetValue(1);
}
dr.Close();
com.Clone();
con.Close();
MemoryStream ms = new MemoryStream(imagebytes);
Bitmap bmpt = new Bitmap(ms);
pictureBox1.Image = bmpt;
}