Oracle .NET 数据提供程序和转换

发布于 2024-08-27 01:21:33 字数 974 浏览 4 评论 0 原文

我使用 Oracle 的特定数据提供程序 (11g),而不是即将停止使用的 Microsoft 提供程序。我发现 ODP.NET 的一个特点是它对数据类型的挑剔。 JDBC 和其他 ADO 提供程序只是进行转换并使其正常工作,而 ODP.NET 将抛出无效的转换异常,除非您完全正确。

考虑以下代码:

        String strSQL = "SELECT DOCUMENT_SEQ.NEXTVAL FROM DUAL";

        OracleCommand cmd = new OracleCommand(strSQL, conn);
        reader = cmd.ExecuteReader();
        if (reader != null && reader.Read()) {
           Int64 id = reader.GetInt64(0);
           return id;
        }

由于 ODP.NET 对转换的挑剔,这不起作用。我通常的选择是:

1)检索到 Decimal 并将其返回到 Int64 (我不喜欢这个,因为 Decimal 太过分了,至少有一次我记得读过它已被弃用......)

Decimal id = reader.GetDecimal(0);
return (Int64)id;

2)或者在 SQL 语句中进行强制转换以确保它适合 Int64,就像

String strSQL = "SELECT CAST(DOCUMENT_SEQ.NEXTVAL AS NUMBER(18)) FROM DUAL";

我做的 NUMBER(18) (2) 一样,因为当我的域类型是 Int32 或 Int64 时,我觉得将数字拉入 .NET Decimal 并不干净。我使用过的其他提供商都足够好(智能),可以即时进行转换。

ODP.NET 专家有什么建议吗?

I use Oracle's specific data provider (11g), not the Microsoft provider that is being discontinued. The thing I've found about ODP.NET is how picky it is with data types. Where JDBC and other ADO providers just convert and make things work, ODP.NET will throw an invalid cast exception unless you get it exactly right.

Consider this code:

        String strSQL = "SELECT DOCUMENT_SEQ.NEXTVAL FROM DUAL";

        OracleCommand cmd = new OracleCommand(strSQL, conn);
        reader = cmd.ExecuteReader();
        if (reader != null && reader.Read()) {
           Int64 id = reader.GetInt64(0);
           return id;
        }

Due to ODP.NET's pickiness on conversion, this doesn't work. My usual options are:

1) Retrieve into a Decimal and return it with a cast to an Int64 (I don't like this because Decimal is just overkill, and at least once I remember reading it was deprecated...)

Decimal id = reader.GetDecimal(0);
return (Int64)id;

2) Or cast in the SQL statement to make sure it fits into Int64, like NUMBER(18)

String strSQL = "SELECT CAST(DOCUMENT_SEQ.NEXTVAL AS NUMBER(18)) FROM DUAL";

I do (2), because I feel its just not clean pulling a number into a .NET Decimal when my domain types are Int32 or Int64. Other providers I've used are nice (smart) enough to do the conversion on the fly.

Any suggestions from the ODP.NET gurus?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦幻的味道 2024-09-03 01:21:33

这将适用于您的原始 SQL:

Int64 id = System.Convert.ToInt64(reader.GetValue(0));

This will work with your original SQL:

Int64 id = System.Convert.ToInt64(reader.GetValue(0));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文