2016-12-13 30 views
0

我想编写一个方法来返回一个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中没有当前行。

任何人都有关于发生了什么的线索?

感谢

+1

读者只是一个指向您的数据的指针。问题是SQLiteConnection超出了范围。你可能想要返回一个项目列表,而不是读者 –

+0

@StuartSmith,但读者有一个引用命令对象,它有一个连接的引用,所以它不能得到GCd,可以吗? – stuartd

回答

0

你需要检查是否有试图获取他们之前的结果。如果你知道肯定有结果只有一个,你可以做

if(reader.Read()) 
{ 
    MessageBox.Show(Convert.ToString(zReader["acText"])); 
} 

如果您预计多行,这样做

while(reader.Read()) 
{ 
    // Code to read rows here 
} 
+0

谢谢,您的解决方案解决了我的问题。 – sevynos

1

您需要完成阅读过程:

public MainWindow() 
    { 
     ... 
     using(SQLiteDataReader zReader = DBUtils.getAction(dbPath, 1)) 
     { 
     if(rdr.Read()) 
     { 
      var someString = rdr.GetString(0); 
      ... 
     } 
     } 
    } 
0

DataReader的总是需要一个开放的连接,从数据库中读取数据,你必须使用Reader.Read方法来得到他们的价值观,所以你需要做的微小变化在你的方法签名是这样的:

public static SQLiteDataReader getAction(string dbPath, byte actionLevel) 
{ 
    SQLiteDataReader reader = null; 

    SQLiteConnection 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(); 
    return reader; 
} 

而在调用方法这些变化必须应用:

SQLiteDataReader zReader = DBUtils.getAction(dbPath, 1); 
while(zReader.Read()) 
{ 
    MessageBox.Show(zReader["acText"].ToString()); 
} 
+0

感谢您的详细解答。如果可能的话,会接受两次答案。 – sevynos