存图片进去:
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName.Trim() != null)
{
openFileDialog1.Filter = "(图片*jpg)|*jpg";
_fileName = openFileDialog1.FileName;
FileStream fs = new FileStream(_fileName, FileMode.OpenOrCreate);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
fs.Close();
try
{
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
SqlCommand com = new SqlCommand("insert into Test(TestID,TestPic,TestName) values(1,@TestPic,'" + _fileName + "')", conn);
com.Parameters.Add("TestPic", SqlDbType.Image);
com.Parameters["TestPic"].Value = data;
int intFalg = com.ExecuteNonQuery();
if (intFalg == 1)
{
MessageBox.Show("保存图片成功");
}
else
{
MessageBox.Show("保存图片失败");
}
conn.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
读取图片:
string sql = "select TestPic from Test where TestID=1";
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] mydata = (byte[])dr[0];
MemoryStream myStream = new MemoryStream(mydata);
Bitmap bit = new Bitmap(myStream);
pictureBox1.Image = bit;
myStream.Close();
}
dr.Close();
conn.Close();
数据库中存图片时用image类型就可以了
前几天正好做了这个方面的东西
看看吧