using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.OracleClient; namespace Learning { /// <summary> /// 本例将图片存储在Oracle中,使用OracleClient连接数据库 /// 使用Oledb操作数据库的话,里面不存在blob类型,当用binary类型代替时出现类型转换错误 /// </summary> public partial class Form1 : Form { OracleConnection conn = new OracleConnection("Data Source=xxx;Persist Security Info=True;User ID=xxx;Password=xxx"); OracleCommand com; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { openFileDialog1.Multiselect = false;//只能选择一个文件 } //浏览并存取图片 private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { //获取文件名 textBox1.Text = openFileDialog1.FileName; //打开文件流 FileStream fs = new FileStream(textBox1.Text, FileMode.Open); //创建文件存放载体 byte[] imgData = new byte[fs.Length]; //填充字节数组 fs.Read(imgData, 0, (int)fs.Length);//long -> int string strInsert = "insert into saveImage(ID,name,img) values(seq_saveImage.nextval,'a',:img)"; com = new OracleCommand (strInsert, conn); com.Parameters.Add("img", OracleType.Blob).Value = imgData; conn.Open(); com.ExecuteScalar(); conn.Close(); } } //从数据库读取文件显示在窗体中 private void button2_Click(object sender, EventArgs e) { string strSelect = "select img from saveImage where id=" + textBox2.Text; com = new OracleCommand(strSelect, conn); conn.Open(); //用oracleLob类型的对象来接收,因为将返回值强制转换为字节数组会报错 OracleLob lob = ((OracleLob)com.ExecuteOracleScalar()); byte[] imageData = new byte[lob.Length]; lob.Read(imageData, 0, (int)lob.Length); conn.Close(); MemoryStream ms = new MemoryStream(imageData); //用流创建图片 Image i = Image.FromStream(ms); //图片显示在pictureBox中 pictureBox1.Image = i; //pictureBox自适应图片大小 pictureBox1.Size = i.Size; } //从数据库中读取二进制流,创建word文档 private void button3_Click(object sender, EventArgs e) { string strSelect = "select img from saveImage where id=" + textBox3.Text; com = new OracleCommand(strSelect, conn); conn.Open(); //用oracleLob类型的对象来接收,因为将返回值强制转换为字节数组会报错 OracleLob lob = ((OracleLob)com.ExecuteOracleScalar()); byte[] imageData = new byte[lob.Length]; lob.Read(imageData, 0, (int)lob.Length); conn.Close(); //文件名:注若启用debug模式运行程序文件生成到./bin/debug下,若为运行方式则生成到./bin/release下 string fileName = textBox3.Text + ".doc"; //创建文件 FileStream f = File.Create(fileName); //把内容写入文件 f.Write(imageData, 0, imageData.Length); } } }