欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

将图片存入Oracle数据库的方法(代码教程)

程序员文章站 2022-07-09 22:16:34
一、将图片存入Oracle数据库 示例表NEWS的结构为:newsid number(10),title varchar2(100),image(blob) 方法1:利用Ora...

一、将图片存入Oracle数据库

示例表NEWS的结构为:newsid number(10),title varchar2(100),image(blob)

方法1:利用OracleCommandBuilder类(该类用于自动生成用于协调 DataSet 的更改与关联的数据库的单表命令。)

        Dim cn As New OracleConnection("data source=site;uid=gf;pwd=macro;") 
        cn.Open() 
 
        Dim da As New OracleDataAdapter("select * from news", cn) 
        Dim myCB As New OracleCommandBuilder(da) 
        Dim ds As New DataSet("news") 
        da.MissingSchemaAction = MissingSchemaAction.AddWithKey 
        Dim fs As Stream = File1.PostedFile.InputStream 'File1为文件选择框,作为服务器控件使用 
        Dim mydata(fs.Length) As Byte 
        fs.Read(mydata, 0, fs.Length) 
        fs.Close() 
        da.Fill(ds, "news") 
        Dim myRow As DataRow = ds.Tables("news").NewRow 
        myRow("newsid") = txtNewsID.Text 
        myRow("title") = txtTitle.Text 
        myRow("image") = mydata 
        ds.Tables("news").Rows.Add(myRow) 
        da.Update(ds, "news") 

方法2:利用过程

事先定义的Oracle过程为:

CREATE OR REPLACE  PROCEDURE "GF"."NEWS_ADD"  
  (in_newsid in  
   news.newsid%type, 
   in_title in news.title%type, 
   in_imag in news.image%type) 
   as 
   begin 
       insert into gf.news values(in_newsid,in_title,in_image); 
   end; 

下面是将数据存入数据库的代码:

        Dim cn As New OracleConnection("data source=site;uid=gf;pwd=macro;") 
        cn.Open() 
 
        Dim cmd As New OracleCommand("news_add", cn) 
        cmd.CommandType = CommandType.StoredProcedure 
        cmd.Parameters.Add(New OracleParameter("in_newsid", OracleType.Number, 10)) 
        cmd.Parameters("in_newsid").Value = txtNewsID.Text.Trim 
        cmd.Parameters.Add(New OracleParameter("in_title", OracleType.VarChar, 100)) 
        cmd.Parameters("in_title").Value = txtTitle.Text.Trim 
 
        Dim fs As Stream = File1.PostedFile.InputStream 
        Dim mydata(fs.Length) As Byte '定义一个字节数组用于读取图片流 
        fs.Read(mydata, 0, fs.Length) 
        fs.Close() 
 
        cmd.Parameters.Add(New OracleParameter("in_image", OracleType.Blob)) 
        cmd.Parameters("in_image").Value = mydata 
 
        cmd.ExecuteNonQuery() 
 
        cn.Close()