无法将 ODBCDATAREADER 加载到数据表

本文关键字:数据表 加载 ODBCDATAREADER | 更新日期: 2023-09-27 18:33:46

我正在使用 Informix 数据库,并且我正在尝试获取特定项目的数据并将其存储在数据表中。

我检查了以下内容:

1( 连接字符串看起来不错

2(连接能够打开

3( 我在创建表适配器的数据集上使用 web.config 中的相同连接字符串,它能够检索记录。

这是我正在使用的代码:

var connectionstring = ConfigurationManager.ConnectionStrings["TestDataTable"].ConnectionString;
OdbcConnection con = new OdbcConnection(connectionstring);
//con.ConnectionString = connectionstring;
if (TxtItem.Text != hold_item)
{
    con.Open();
    OdbcCommand cmd = new OdbcCommand(@"Select t_item,t_idsc,t_upct,
                                        t_item_upc,t_ctyp,t_citg,
                                        t_best,t_disp,t_mold,t_csel 
                                        from informix.tsckcm907
                                        where t_item = " + stitem, con); 
    OdbcDataReader myReader = cmd.ExecuteReader();
    DataTable testdt = new DataTable();
    testdt.Load(myReader);
    foreach (DataRow row in testdt.Rows)
    {
       lbldesc.Text = row["t_idsc"].ToString();
       Spanish_Item();
       {
           DropDownList2.SelectedIndex = 1;
           object stlanguage = 1;
           hold_language = Convert.ToString(stlanguage);
           TxtBestBefore.Text = row["t_best"].ToString();
           holdbest = Convert.ToInt16(TxtBestBefore.Text);
       }
   }
   myReader.Close();
   myReader.Dispose();
   cmd.Dispose();
   con.Close();
   con.Dispose();
}

在调试模式下,我的错误发生在 OdbcDataReader 行:错误信息:

An exception of type 'System.Data.Odbc.OdbcException' 
occurred in System.Data.dll but was not handled in user code
Additional information: ERROR [42000] [Informix]
[Informix ODBC Driver][Informix]A syntax error has 
occurred.

无法将 ODBCDATAREADER 加载到数据表

如果您的 Informix ODBC 驱动程序显示:"发生了语法错误",那么您必须检查您的 SQL 语句:

"Select t_item,...  from informix.tsckcm907 where t_item = " + stitem

我认为stitem有问题.我们不知道它是什么类型和值,但如果它的类型是某种字符串或日期,那么它可能采用错误的形式。最简单的方法是提取完整的SQL语句(只需在执行前打印它(并将其与某些数据库编辑器(例如Informix中的db_access(一起使用。然后让它在SQL编辑器中工作stitem并将变量转换为可接受的形式(添加引号,转义内部引号,转义特殊字符等(

我还建议使用 PreparedStatement 将您的查询与数据分开。这样,您无需担心stitem形式。没有引号,没有转义,只有查询字符串中的占位符和单独添加的值。

我不使用 C#,但我看到 C# 可以使用带有未命名参数的预置语句:

cmd.CommandText = "SELECT ... FROM ... WHERE t_item = ?";
cmd.Parameters.Add("@t_item", ObdcType.VarChar, 200).Value = t_item;

或使用命名参数:

cmd.CommandText = "SELECT ... FROM ... WHERE t_item = @t_item";
cmd.Parameters.Add("@t_item", ObdcType.VarChar, 200).Value = t_item;

我使用 ODBC 中的未命名参数,因此 Informix 驱动程序可以使用此类参数,但您必须使用 C# 自己检查它。