schocka94
schocka94

Reputation: 41

Cannot open Sqlite Database in asp.net

My project should display data from an sqlite3 database. The database name is db.sqlite3. The error is: Unable to open the database file

here is my code:

public partial class OverviewAdmin : System.Web.UI.Page
    {

        private SQLiteConnection sql_con;
        private SQLiteCommand sql_cmd;
        private SQLiteDataAdapter DB;
        private DataSet DS = new DataSet();
        private DataTable DT = new DataTable();


        protected void Page_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void SetConnection()
        {
            sql_con = new SQLiteConnection
                ("Data Source=db.sqlite3;");
        }

        private void LoadData()
        {
            SetConnection();
            sql_con.Open();
            sql_cmd = sql_con.CreateCommand();
            string CommandText = "select * from scotty_fahrt";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            GVOutput.DataSource = DT;
            sql_con.Close();
        }

Maybe its because of the database file name.

Upvotes: 0

Views: 1453

Answers (1)

Steve
Steve

Reputation: 216293

Put your database file in the APP_DATA subfolder of your site and change the method that sets the connection to

    private void SetConnection()
    {
        sql_con = new SQLiteConnection
            ("Data Source=|DataDirectory|\\db.sqlite3;");
    }

By the way, I would remove the global variable for the connection and change your SetConnection to return the SQLiteConnection. This will allow to apply the using statement to correctly handle disposable like a connection also in case of exceptions

    private SQLite GetConnection()
    {
        return new SQLiteConnection("Data Source=|DataDirectory|\\db.sqlite3;");
    }

    private void LoadData()
    {
        using(SQLiteConnection cn = GetConnection())
        {
            cn.Open();
            string CommandText = "select * from scotty_fahrt";
            DB = new SQLiteDataAdapter(CommandText, sql_con);
            DS.Reset();
            DB.Fill(DS);
            DT = DS.Tables[0];
            GVOutput.DataSource = DT;
        }
    }

Upvotes: 3

Related Questions