//将图片转化为字节数组写入数据库
private void button3_Click(object sender, EventArgs e)
{
string _filePath = Application.StartupPath + "\\index1.jpg";
FileStream _stream = new FileStream(_filePath, FileMode.Open,FileAccess.Read);
byte[] _aryByte = new byte[_stream.Length];
_stream.Read(_aryByte, 0, _aryByte.Length);
string _sConnection = "Provider=SQLOLEDB;Data Source=127.0.0.1;Initial Catalog=Northwind;User Id=sa;Password=";
OleDbConnection _conn = null;
try
{
_conn = new OleDbConnection(_sConnection);
_conn.Open();
//通过OLEDB连接,参数为?,如果使用ado连接,参数为@参数名
string _sql = "insert into TestImage(UserName,Image)values(?,?)"; OleDbCommand _command = new OleDbCommand(_sql, _conn);
_command.CommandType = CommandType.Text;
_command.Parameters.Add("?", OleDbType.VarChar, 255).Value = "lins";
_command.Parameters.Add("?", OleDbType.Binary).Value = _aryByte;
_command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
_conn.Close();
_conn = null;
}
}
//从数据库中读取图片
private void button4_Click(object sender, EventArgs e)
{
string _sConnection = "Provider=SQLOLEDB;Data Source=127.0.0.1;Initial Catalog=Northwind;User Id=sa;Password=";
OleDbConnection _conn = null;
try
{
_conn = new OleDbConnection(_sConnection);
_conn.Open();
string _sql = "select Image from TestImage where username = 'lins'";
OleDbCommand _command = new OleDbCommand(_sql, _conn);
OleDbDataReader _reader = _command.ExecuteReader();
while (_reader.Read())
{
byte[] _ary = (byte[])_reader["image"];
MemoryStream _stream = new MemoryStream(_ary);
Image _img = Image.FromStream(_stream);
Graphics _g = this.CreateGraphics();
_g.DrawImage(_img, new Point(0, 0));
}
_command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
_conn.Close();
_conn = null;
}
}