C# 读取和写入oracle的blob字段的方法

 //向数据库中写入

        private void button1_Click(object sender, EventArgs e)

        {

            oracleConnection1.Open();

          

            OracleCommand cmd = new OracleCommand("UPDATE TEST SET F2 =:blob where F1=:sn ", oracleConnection1);

           

            cmd.Parameters.Add(new OracleParameter("blob",OracleType.Blob));

              cmd.Parameters.Add(new OracleParameter("sn",OracleType.Int32));

             FileInfo fi = new FileInfo("c://dos.doc");

             FileStream fs = fi.OpenRead();

             byte[] MyData = new byte[fs.Length];

             fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));

             fs.Close();

            cmd.Parameters["blob"].Value = MyData;

            cmd.Parameters["sn"].Value = 1;

            try

            {

                int result = cmd.ExecuteNonQuery();

                if (result < 1)

                {

                    System.Console.WriteLine("插入数据错误!");

                }

                else

                    System.Console.WriteLine("插入数据成功!");

            }

            catch (Exception e1)

            {

                System.Console.WriteLine("插入数据错误!"+e1.ToString());

            }

            finally

            {

                oracleConnection1.Close();

            }

 

        }

//从数据库中读取

        private void button2_Click(object sender, EventArgs e)

        {

            oracleConnection1.Open();

            oracleCommand1.CommandText = "select * from TEST where f1=1";

            OracleDataReader rs = oracleCommand1.ExecuteReader();

            while (rs.Read())//读取数据,如果odr.Read()返回为false的话,就说明到记录集的尾部了

            {

                byte[] File=(byte[])rs["F2"];

                   FileInfo fi=new FileInfo("c://new.doc");

                   FileStream fs=fi.OpenWrite();

                   fs.Write(File,0,File.Length);

                   fs.Flush();

                fs.Close();

           

            }

            rs.Close();

        }

 

 

你可能感兴趣的:(数据库,oracle,c#,byte,button,exception,object)