您的位置:首页 > 数据库 > Oracle

关于文件保存到Oracle中BLOB字段的方法及例子

2011-10-12 13:21 435 查看
关于文件保存到Oracle中BLOB字段的方法及例子
-------------------------------------------
public class FileOpClass
{
public static byte[] GetFileStream(string filepath)
{
byte[] byteArray = null;
FileStream fs = null;
try
{
fs = new FileStream(filepath, FileMode.Open);
long filelength = fs.Length;
byteArray = new byte[filelength];
fs.Read(byteArray, 0, byteArray.Length);
}
catch (Exception ee)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
fs = null;
}
}
return byteArray;
}
public static void WriteToFile(byte[] byteArray, string filepath)
{
if (System.IO.File.Exists(filepath) == true)
{
try
{
System.IO.File.Delete(filepath);
}
catch { }
}
FileStream fs = null;
try
{
fs = new FileStream(filepath, FileMode.OpenOrCreate);
fs.Write(byteArray, 0, byteArray.Length);
fs.Flush();
}
catch (Exception ee)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
fs = null;
}
}
}
}
//------------------------------------------
先插入一条objblob字段为空的记录,用insert into tablename(objid,objname) values('xxx','yyyy');
然后对objblog字段作update方式操作
//------------------------------------------
byte[] byteArray =FileOpClass.GetFileStream(path);
object UpdateBLOBFdValue=byteArray;

//------------------------------------------
//更新BLOB字段值的方法
//------------------------------------------
public bool UpdateBLOBFieldValue(string UpdateTableName, string UpdateBLOBFieldName, object UpdateBLOBFdValue, string WhereEqFieldName, string WhereEqFdValue)
{
bool rbc = false;
DatabaseHelperClass dbh = new DatabaseHelperClass(m_Database);
DbConnection dbconn = null;
DbTransaction dbtrans = null;  //Provider=OraOleDb.Oracle;
DbCommand dbCmd1 = null;
try
{
dbconn = dbh.db.CreateConnection();
if (dbconn.State != ConnectionState.Open)
{
dbconn.Open();
}
dbtrans = dbconn.BeginTransaction();

string PrixChar = dbh.PrixChar;
string x = "update " + UpdateTableName + " set " + UpdateBLOBFieldName + "=" + PrixChar + "Img where " + WhereEqFieldName + "=" + PrixChar + "tmpguid ";
byte[] byteArray = UpdateBLOBFdValue as byte[];
//
dbCmd1 = dbconn.CreateCommand();
dbCmd1.CommandText = x;
dbCmd1.CommandType = CommandType.Text;
dbCmd1.Connection = dbconn;
dbCmd1.Transaction = dbtrans;
//
DbParameter dbparam = dbh.CreateParameter("" + PrixChar + "Img", byteArray);
dbparam.Direction = ParameterDirection.Input;
dbparam.DbType = System.Data.DbType.Binary;
dbparam.Value = byteArray;
dbCmd1.Parameters.Add(dbparam);
dbCmd1.Parameters.Add(dbh.CreateParameter("" + PrixChar + "tmpguid", WhereEqFdValue));
if (dbCmd1.ExecuteNonQuery() > 0)
{
rbc = true;
dbtrans.Commit();
}
}
catch (Exception ee)
{
if (dbtrans != null)
{
dbtrans.Rollback();
}
rbc = false;
}
finally
{
if (dbCmd1 != null)
{
dbCmd1.Dispose();
dbCmd1 = null;
}
//----
if (dbtrans != null)
{
dbtrans.Dispose();
dbtrans = null;
}
if (dbconn != null)
{
dbconn.Dispose();
dbconn = null;
}
}
return rbc;
}
----the---end-------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: