c#操作oracle lob字段[转自 芽芽的回收站]

public static void WriteClob(string table_name, string fieldname ,string table_id, string id, int column, string content)
{
OracleConnection myCn = OracleModel.GetConnection(DbKey.ORA);
OracleCommand myCmd = new OracleCommand();
try
{
myCn.Open();
}
catch (System.Data.OracleClient.OracleException e)
{
throw new Exception(e.Message);
}
OracleTransaction myTrans = myCn.BeginTransaction();
try
{
myCmd.Connection = myCn;
myCmd.Transaction = myTrans;
myCmd.CommandText = "SELECT "+fieldname+" FROM " + table_name + " where " + table_id + " = '" + id + "' FOR UPDATE";
OracleDataReader reader = myCmd.ExecuteReader();
using (reader)
{
reader.Read();
OracleLob CLOB = reader.GetOracleLob(column); //column为lob类型所在列
Encoding utf16 = Encoding.Unicode;       
byte[] buffer = utf16.GetBytes(content);
if (buffer.Length % 2 == 0)
CLOB.Write(buffer, 0, buffer.Length);  //这里的参数必须为偶数
else
CLOB.Write(buffer, 0, (buffer.Length - 1));
myTrans.Commit();
}
}
catch (System.Data.OracleClient.OracleException e)
{
myTrans.Rollback();
}
finally
{
myCmd.Dispose();
myCn.Close();
}
}
public static string ReadClob(string table_name, string fieldname,string table_id, string id, int column)
{
OracleConnection myCn = OracleModel.GetConnection(DbKey.ORA);
OracleCommand myCmd = new OracleCommand();
try
{
myCn.Open();
}
catch (System.Data.OracleClient.OracleException e)
{
throw new Exception(e.Message);
}
OracleTransaction myTrans = myCn.BeginTransaction();
try
{
myCmd.Connection = myCn;
myCmd.Transaction = myTrans;
myCmd.CommandText = "SELECT "+fieldname+" FROM " + table_name + " where " + table_id + " = '" + id + "'";
OracleDataReader reader = myCmd.ExecuteReader();
using (reader)
{
reader.Read();
OracleLob CLOB = reader.GetOracleLob(column);

byte[] buffer = new byte[(int)CLOB.Length];
CLOB.Read(buffer,0,(int)CLOB.Length);

Encoding utf16 = Encoding.Unicode;
string final = utf16.GetString(buffer);
myTrans.Commit();
return final;
}
}
catch (System.Data.OracleClient.OracleException e)
{
myTrans.Rollback();
return "";
}
finally
{
myCmd.Dispose();
myCn.Close();
}
}

你可能感兴趣的:(oracle)