为什么我得到"没有与此命令关联的连接"?

sch*_*a94 2 c# asp.net sqldatareader

我的问题是我的datareader没有用.

这是我的代码:

SQLiteCommand comID = new SQLiteCommand("Select max(id) from haltestellen");
conSQLiteDb.Open();
SQLiteDataReader dr = comID.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
    LblHaltestelleID1.Text = dr.GetValue(0).ToString();
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 7

只需使用适当的构造函数.作为连接的第二个参数的重载将您的命令与用于执行所需的sql语句的连接相关联.

 SQLiteCommand comID = new SQLiteCommand("Select max(id) from haltestellen", conSQLiteDb);
 conSQLiteDb.Open();
 SQLiteDataReader dr = comID.ExecuteReader(CommandBehavior.CloseConnection);
 if (dr.Read())
 {
    LblHaltestelleID1.Text = dr.GetValue(0).ToString();
 }
Run Code Online (Sandbox Code Playgroud)

您还可以使用命令属性Connection

 SQLiteCommand comID = new SQLiteCommand("Select max(id) from haltestellen");
 comID.Connection = conSQLiteDb;
 conSQLiteDb.Open();
Run Code Online (Sandbox Code Playgroud)