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.OleDb;
using System.IO;
namespace SendEMail
{
public partial class frmSaveImg : Form
{
OleDbConnection conn;
public frmSaveImg()
{
InitializeComponent();
//OleDbConnection连接字符串
string strConn = @"provider=Microsoft.Jet.OLEDB.4.0;data source=" + Application.StartupPath + "\\db1.mdb";
//创建OleDbConnection对象
conn = new OleDbConnection(strConn);
}
/// <summary>
/// 执行SQL语句函数
/// </summary>
/// <param name="sqlcmd">SQL语句</param>
/// <param name="paras">SQL语句中的参数组</param>
/// <returns>返回受影响记录条数</returns>
public int ExecuteSql(string sqlcmd,params OleDbParameter[] paras)
{
OleDbCommand cmd = new OleDbCommand(sqlcmd, conn);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
foreach (OleDbParameter p in paras)
{
cmd.Parameters.Add(p);
}
int cnt = cmd.ExecuteNonQuery();
conn.Close();
return cnt;
}
/// <summary>
/// 执行SQL查询
/// </summary>
/// <param name="sqlcmd">SQL语句</param>
/// <returns>返回数据表</returns>
public DataTable QuerySql(string sqlcmd)
{
OleDbDataAdapter oda = new OleDbDataAdapter(sqlcmd, conn);
DataTable dt = new DataTable();
oda.Fill(dt);
return dt;
}
//单击pictureBox1是执行
private void pictureBox1_Click(object sender, EventArgs e)
{
//打开文件对话框
OpenFileDialog ofd = new OpenFileDialog();
//选择图片后,点击确定按钮,加载图片
if (ofd.ShowDialog() == DialogResult.OK)
{
pictureBox1.ImageLocation= ofd.FileName;
}
}
//单击保存按钮执行图片保存到数据库中
private void button1_Click(object sender, EventArgs e)
{
//插入数据SQL语句, img字段为表中存储图片的字段(ole类型)
string sql = "insert into tb_img (img) values (@img)";
//读取图片文件流
FileStream fs = File.Open(pictureBox1.ImageLocation, FileMode.Open, FileAccess.Read);
//将流转化为byte数组
byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, MyData.Length);
fs.Close();
//给SQL语句中的参数@img, 赋值
OleDbParameter p = new OleDbParameter("@img", MyData);
//执行SQL语句,将数据插入表中
ExecuteSql(sql, p);
//刷新comboBox1
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "id";
comboBox1.DataSource = QuerySql("select id from tb_img");
}
//当comboBox1的index改变时执行
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//得到当前comboBox1选中的记录
DataTable dt = QuerySql("select * from tb_img where id =" + comboBox1.SelectedValue.ToString());
//将值强转为byte数组
byte[] MyData = (byte[])dt.Rows[0]["img"];
//将byte[]数组写入到流中
MemoryStream s = new MemoryStream();
s.Write(MyData, 0, MyData.Length);
//pictureBox1加载得到的流
pictureBox1.Image = Image.FromStream(s);
}
//窗体启动时,comboBox1绑定数据库
private void frmSaveImg_Load(object sender, EventArgs e)
{
comboBox1.ValueMember = "id";
comboBox1.DisplayMember = "id";
comboBox1.DataSource = QuerySql("select id from tb_img");
}
}
}
C#数据库保存图片
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
上一篇:JSP九大内置对象
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章