C# 无法将odbcdatareader加载到数据表
我使用的是Informix数据库,我试图获取特定项的数据并将其存储在datatable中 我检查了以下内容: 1连接字符串看起来不错 2连接能够打开 3我在创建表适配器的数据集上使用了web.config中的相同连接字符串,并且它能够检索记录 这是我正在使用的代码:C# 无法将odbcdatareader加载到数据表,c#,asp.net,odbc,informix,executereader,C#,Asp.net,Odbc,Informix,Executereader,我使用的是Informix数据库,我试图获取特定项的数据并将其存储在datatable中 我检查了以下内容: 1连接字符串看起来不错 2连接能够打开 3我在创建表适配器的数据集上使用了web.config中的相同连接字符串,并且它能够检索记录 这是我正在使用的代码: var connectionstring = ConfigurationManager.ConnectionStrings["TestDataTable"].ConnectionString; OdbcConnection con
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.
如果Informix ODBC驱动程序显示:发生语法错误,则必须检查SQL语句:
"Select t_item,... from informix.tsckcm907 where t_item = " + stitem
我觉得斯泰姆有点不对劲。我们不知道它是什么类型和值,但是如果它的类型是某种字符串或日期,那么它的形式可能是错误的。最简单的方法是提取完整的SQL语句,只需在执行之前将其打印出来,并与一些数据库编辑器(例如Informix中的db_access)一起使用。然后让它在SQL编辑器中工作,并将stitem变量转换为可接受的形式:添加引号、转义内部引号、转义特殊字符等
我还建议使用PreparedStatement将查询与数据分开。这样,您就不必担心拼接形式。并没有引号,并没有转义,只是在查询字符串中分别放置holder和value added
我不使用C,但我看到C可以使用带有未命名参数的PrePred语句:
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;
或使用命名参数:
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检查。如果使用字符串连接,则stitem的实际值是多少,在许多级别上都非常糟糕,包括值中存在一个引号。如果t_item是一个文本字段,那么需要在变量周围加引号