【问题标题】:How to read a CLOB field into a C# variable? [duplicate]如何将 CLOB 字段读入 C# 变量? [复制]
【发布时间】:2012-09-16 11:19:59
【问题描述】:

可能重复:
Why Do I get OutOfRange Exception in GetOrdinal Function of this CLOB field?

I need to read a CLOB field from an ORACLE table int a C# variable of type String. Does anyone know how to accomplish this task? 

这就是我所做的,但是在计算字段的 GetOrdinal 时我得到了 IndexOutofRange。提前致谢。

 public void ReadFunction(string FName, out string fContent) 
{ 
    OracleCommand command = _connection.CreateCommand(); 
    OracleTransaction transaction = _connection.BeginTransaction(); 
    command.Transaction = transaction; 
    command.CommandText = "SELECT TO_CLOB(TO_NCLOB(FUNCTION_SCRIPT)) FROM IS_FUNCTION where   FNAME=:fName "; 
    command.Parameters.Add("FName", OracleType.NVarChar).Value = FName; 
    OracleDataReader odr = command.ExecuteReader(); 
    int temp = odr.GetOrdinal("FUNCTION_SCRIPT"); 
    OracleLob myLob = odr.GetOracleLob(temp); 
    fContent = (String)myLob.Value; 
    odr.close(); 
} 

【问题讨论】:

  • 我非常需要帮助,我想也许我需要改进我的问题标题。
  • @user1298925 那么您应该编辑原始问题的标题。
  • 哦好的,谢谢你的建议。

标签: c# sql oracle select


【解决方案1】:

这是获取 Blob 的代码,然后您应该按照您需要的方式将其转换为字符串。我不知道你需要的格式。

  // create and open connection
  // change for your environment
  string connStr = "User Id=pm; Password=pm; Data Source=orcllx; Pooling=false";
  OracleConnection con = new OracleConnection(connStr);
  try
  {
    con.Open();
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message);
  }

  // statement to get a blob
  string sql = "select ad_composite from print_media where product_id=3106 and
               ad_id=13001";

  // create command object
  // InitialLOBFetchSize
  //  defaults to 0
  OracleCommand cmd = new OracleCommand(sql, con);

  cmd.InitialLOBFetchSize = 8192;

  // create a datareader
  OracleDataReader dr = cmd.ExecuteReader();

  // read the single row result
  try
  {
    dr.Read();
  }
  catch (OracleException ex)
  {
    MessageBox.Show(ex.Message);
  }

  // use typed accessor to retrieve the blob
  OracleBlob blob = dr.GetOracleBlob(0);

  // create a memory stream from the blob
  MemoryStream ms = new MemoryStream(blob.Value);

  // set the image property equal to a bitmap
  // created from the memory stream
  pictureBox1.Image = new Bitmap(ms);

【讨论】:

  • dr.Read() 是缺失的链接。 .顺便说一句,有人告诉我,如果您在 sql Select 语句中包含数据,这被认为是需要避免的 SQL 注入攻击。我以为我会与您分享那条知识。希望有用。
  • 我不必设置InitialLOBFetchSize - 我猜可能没有必要,但也不错。将 blob 转换为字节数组实际上很常见,这可以通过 byte[] array = new byte[blob.Length]; blob.Read(array, 0, (int)array.Length); 完成。实际上,它应该使用if (dr.HasRows) { ... } 条件,然后在其中检索 blob,所有这些都将进入内部。在 WPF 中,您必须创建一个新的 BitmapImage 并将其分配给它的 StreamSource 一个 MemoryStream,就像上面一样,但还有一些其他选项需要声明 (BitmapCreateOptions, BitmapCacheOption)。
  • 问题是关于 CLOB,而不是 BLOB...
猜你喜欢
  • 2016-06-02
  • 2014-09-30
  • 2014-04-28
  • 2022-01-09
  • 2013-07-14
  • 2016-07-12
  • 2019-12-27
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多