in

System.Data.SQLite

An open source ADO.NET provider for the SQLite database engine

C#.net Beginner's Code

Last post 06-22-2009 3:36 PM by gwar3k1. 4 replies.
Page 1 of 1 (5 items)
Sort Posts: Previous Next
  • 06-21-2009 11:03 AM

    C#.net Beginner's Code

    I'm trying to have a generic function for SQL queries with the output being a datareader. I'm getting a database locked error when running my code though, so I put a dbconn.close before my return but then I get an error saying the connection is closed and so the data no longer is in the reader to return. Catch 22. I think I must be going about this the wrong way. Can anyone point me in the direction of tutorials that don't use scalar and are relevant to C#.net? Or at least, could someone suggest a different method for doing this:


    public static SQLiteDataReader ExecuteQuery(string strSql)
    {
     SQLiteConnection dbConn = new SQLiteConnection("Data Source=" + dbPath + @"\" + dbName);
     dbConn.Open();

     SQLiteCommand sqlQ = new SQLiteCommand(dbConn);
     sqlQ.CommandText = strSql;

     SQLiteDataReader sqlReader = sqlQ.ExecuteReader();
     dbConn.Close();

     return sqlReader;
    }

     

    SQLiteDataReader sqlReader;
    sqlReader = SQL.ExecuteQuery("SELECT count(FilePath) FROM files WHERE FilePath = '" + strSPath + "';");

  • 06-21-2009 12:59 PM In reply to

    Re: C#.net Beginner's Code

     Why not keep your connection open while your program is running?

    Edit: I did not read your post well.   I did not see you have a locked error.  Is this when executing your command?

    Luc Wuyts
    http://www.a-d-e.net
  • 06-21-2009 11:47 PM In reply to

    Re: C#.net Beginner's Code

    No, it's when I execute another command following the first one. Because I don't close the connection, I get a locked error. Would opening the connection at program start prevent this?

    What options do I have when opening a connection to prevent locking of tables?

  • 06-22-2009 8:52 AM In reply to

    Re: C#.net Beginner's Code

    You need to dispose of the datareader when you're done with it, with using() statements.

    using (SQLiteDataReader sqlReader = SQL.ExecuteQuery("select whatever from whatever"))
    {
      // ... do your code here
    }

    The problem is you're leaving the datareader's hanging, at which point they lazily go to the garbage collector to get GC'd whenever the collector gets around to it.

  • 06-22-2009 3:36 PM In reply to

    Re: C#.net Beginner's Code

     Thanks, this work but where do I close the connection? I've returned a reader from my SQL class to the program class so I can't add it to the function. Should I abstract dbConn to a public variable as suggested and have a close procedure to call from the program class?

Page 1 of 1 (5 items)
Powered by Community Server (Commercial Edition), by Telligent Systems