我想编写一个方法来返回一个SQLiteDataReader对象,但没有任何成功。在c中返回datareader#
这里的方法的源代码:
在一类文件(DBUtils.cs):
public static SQLiteDataReader getAction(string dbPath, byte actionLevel)
{
SQLiteConnection m_dbConnection;
SQLiteDataReader reader = null;
m_dbConnection = new SQLiteConnection("Data Source=" + dbPath + ";Version=3;FailIfMissing=True");
m_dbConnection.Open();
string sql = "SELECT * FROM Actions WHERE acLevel=" + actionLevel + " ORDER BY RANDOM() LIMIT 1";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return reader;
}
在主窗口:
public MainWindow()
{
InitializeComponent();
const string dbPath = "../../TestDatabase.sqlite";
SQLiteDataReader zReader = DBUtils.getAction(dbPath, 1);
MessageBox.Show(Convert.ToString(zReader["acText"]));
}
现在,当我跑步步当我在getAction()方法中时,我确实看到数据已从数据库中加载,但当它回到消息框时,我得到一个非法异常,因为DataReader中没有当前行。
任何人都有关于发生了什么的线索?
感谢
读者只是一个指向您的数据的指针。问题是SQLiteConnection超出了范围。你可能想要返回一个项目列表,而不是读者 –
@StuartSmith,但读者有一个引用命令对象,它有一个连接的引用,所以它不能得到GCd,可以吗? – stuartd