0

I created a helper class for Sqlite in C# (using Data.SQLite) where I am putting methods like GetTables,GetColumnNames,...

Now I added method AttachDatabase to attach a database but it does not seem to be working.

The code for this method is as follows

    public void AttachDatabase(string path)
    {
        string db_name = "attdb";
        sqlConnection.Open();

        SQLiteCommand scom = new SQLiteCommand(sqlConnection);
        scom.CommandText = "ATTACH '"+path+"' AS " + db_name;

        scom.ExecuteNonQuery();

        sqlConnection.Close();
    }

The method does not throw any exceptions, when I provide a path to a database file.


And to test it I added another method in helper class that is like this

    public List<string> GetAllDatabases()
    {
        List<string> mylist = new List<string>();

        sqlConnection.Open();
        SQLiteCommand scom = new SQLiteCommand("PRAGMA database_list", sqlConnection);
        SQLiteDataReader sreader = scom.ExecuteReader();

        while (sreader.Read())
        {
            string name = (sreader.GetValue(1)).ToString();
            mylist.Add(name);
        }
        sqlConnection.Close();

        return mylist;
    }

After attaching a database, this method returns a list with only main table in it.

What am I doing wrong?

1
  • What are you trying to achieve? Commented Apr 18, 2012 at 6:55

1 Answer 1

3

Sqlite does not persist the attached databases. Every time you open and close the connection, the attached databases are forgotten.

Sign up to request clarification or add additional context in comments.

2 Comments

Should I then just keep the connection open in the helper class instead of opening/closing connection in each method as it is now? I only intend to use sqlite for desktop apps.
There is no generic answer to that question. If you only have one application accessing the DB at a time then I think it is fine to use the same connection (though there are some gotchas regarding multiple threads). If you want to just get information about a database file, then you could open a single connection to that file and query that file without a need to attach the file. it all depends on your circumstances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.