【问题标题】:Using recordset values in SQL Server 2008 R2在 SQL Server 2008 R2 中使用记录集值
【发布时间】:2015-03-02 12:03:01
【问题描述】:

我使用 Dynamics AX 2012 和 C# 中的业务连接器通过 odbc 方法检索数据。

我使用的是 SQL Server 2008 R2(版本 10.50.2500 - 不是 AX 数据库)。

代码如下所示:

using MIL = Miceoaodr.Dynamics.AX.ManagedInterop;
...
namespae mynamespace
{
   public class myclass
   {
     public static MIL.Session axSession = null;
     ...
     public void test()
     {
        MIL.Container c;
        OdbcDataReader r;
        OdbcConnection conn;
        OdbcCommand cmd;
        object o;
        conn = new OdbcConnection("my connection string");
        conn.open();
        cmd = new OdbcCommand("select * from mytable", conn);

        r = cmd.ExecuteReader();
        while (r.Read())
        {
           c.clear();
           for (int i = 0; i < reader.FieldCount; i++)
           {
              o = reader.getValue(i);
              c.Add(o); // **** fails sometimes
           }

        }
        c = new MIL.Container();
        c.add(0); // **** here is the problem. program halts without any **** warning!
     }
   }
}

带星号的行有时会失败(c.add(0)...)。

似乎只有在 db 中的类型为 int 的表列失败,或者对于值 = 0 的 bigint 类型。

我应该怎么做才能使订单代码不会像描述的那样失败?

谢谢:)

【问题讨论】:

  • 您看到的实际错误是什么?
  • 我没有发现错误。我在stackoverflow.com/questions/1058322/… 上看到博客我认为我应该在 sqltype 到 .net 类型之间进行转换,但我没有找到任何进行这种转换的类。谢谢:)
  • 如果 c.add(o) 有时会失败,应该很容易在它周围放置一个 try catch 并找出失败的原因?
  • 不,我知道为什么会失败。 sql(sqldbtype)中的类型与.net类型不同,所以我需要对其进行转换。谢谢:)

标签: c# sql-server sql-server-2008-r2 axapta dynamics-ax-2012


【解决方案1】:

可以通过多种方式从 odbc 填充数据,而不仅仅是 odbcDataReader(这种方式很不方便,因为需要逐条记录)。

使用 OdbcDataAdapter 类时,如链接https://msdn.microsoft.com/en-us/library/system.data.odbc.odbcdataadapter%28v=vs.110%29.aspx

以下代码也可能有所帮助:

...
OdbcDataAdapter d;
DataTable dt;
d = new OdbcDataAdapter(cmd);
d.Fill(dt);
... 
foreach (DataRow row in dt.Rows)
{
   foreach (DataColumn column in dt.Columns)
   { // fill the column header for the first time by column.ColumnName.
   }
   foreach (DataColumn column in dt.Columns)
   { // fill the colum values using row[column] combination.
   }
}

无需将值从数据库类型转换为 .net 类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多