C# ODBCDataReader有行,但无法访问数据
因此,在C#中,我有一个ODBCDataReader,它返回它有行,但当我尝试访问数据时,它返回一个未设置为对象错误引用的对象。我直接在db上测试了sql,它返回的行没有任何空值C# ODBCDataReader有行,但无法访问数据,c#,database,C#,Database,因此,在C#中,我有一个ODBCDataReader,它返回它有行,但当我尝试访问数据时,它返回一个未设置为对象错误引用的对象。我直接在db上测试了sql,它返回的行没有任何空值 OdbcDataReader results; try { // Initialize & open odbc connection using (OdbcConnection conn = new OdbcConnection(connectionString.ToString())) { conn.
OdbcDataReader results;
try
{
// Initialize & open odbc connection
using (OdbcConnection conn = new OdbcConnection(connectionString.ToString()))
{
conn.Open();
// Initialiaze odbc command object
using (OdbcCommand comm = new OdbcCommand(query.ToString(), conn))
{
results = comm.ExecuteReader();
}
}
}
catch
{
//detailed error messaging here (which does not get hit)
}
temp = results;
if (temp.HasRows == false)
{
//error messaging here does not get hit.
}
while (temp.Read())
{
try
{
//I attempted to access the data by creating an object array:
object [] objarray = new object[temp.FieldCount)
temp.GetValues(objarray); //this causes error
}
catch{ // error is caught here "object not set to a reference of an object" }
for (i = 0; i < temp.FieldCount; i++)
{
try
{
//I also attempted other ways to access the data including:
temp[i].ToString(); // this causes error
temp.GetInt32(i).ToString(); // this causes error
temp.GetName(i); //this causes error
}
catch
{
// error is caught here "object not set to a reference of an object"
}
}
}
OdbcDataReader结果;
尝试
{
//初始化并打开odbc连接
使用(OdbcConnection conn=new OdbcConnection(connectionString.ToString()))
{
conn.Open();
//初始化odbc命令对象
使用(OdbcCommand comm=newodbccommand(query.ToString(),conn))
{
结果=comm.ExecuteReader();
}
}
}
抓住
{
//此处的详细错误消息(未命中)
}
温度=结果;
if(temp.HasRows==false)
{
//此处的错误消息未被命中。
}
while(temp.Read())
{
尝试
{
//我试图通过创建对象数组来访问数据:
object[]objarray=新对象[temp.FieldCount)
temp.GetValues(objarray);//这会导致错误
}
catch{//此处捕获错误“对象未设置为对象的引用”}
对于(i=0;i
您正在using块外部使用它。将使用[results]的部分移动到using块内部(在ExecuteReader()调用之后立即移动)你应该在一个更好的地方。我遇到了同样的问题。我的问题是我没有正确绑定参数。我是使用@
绑定的:
SELECT * FROM MyTable WHERE MyField = @MyField
出于某种原因,这在MySQL中是有效的,不会产生错误,但不会返回数据。解决方案是使用?
绑定:
SELECT * FROM MyTable WHERE MyField = ?
然后在C#中绑定参数:
cmd.Parameters.AddWithValue("@MyField", myFieldValue);
老问题,但这是Google上的第一个结果,没有得到回答。希望有帮助。我试图发布答案,但没有显示,所以我将在这里尝试。问题不在于代码(它工作正常),而是数据库同步问题。