문제

I'm new to Android.

I am using Xamarin on Visual Studio and coding in C#.

I've seen samples of creating a database if it does not exist, but not what I'm looking for.

Does anyone have any code (C#) for using existing sqlite database already in Assets folder, instead of creating new database on Android device?

도움이 되었습니까?

해결책

You have to copy the database file from your Assets folder to somewhere on the device, and then use that in your application. Note that you only have to do this once, when your application first starts up.

다른 팁

Opening an existing SQLite database differs very little from creating a new one.

Assuming you are using sqlite-net (which you should),
all you need to do is create a class that inherits from SQLiteConnection.

public class CustomerDatabase : SQLiteConnection
{
    public CustomerDatabase(string filename) : base(filename, true)
    {
        //This will open the database file specified by filename
    }   
}

If the specified filename refers to an existing database, the database will be openened.
If it refers to a file that does not exist, an attempt will be made to create a new database.

At this point I'm going to assume you have 2 issues:

  1. You want to open and manipulate the database even if you do not have
    the model defined as part of your application. Which means your application has
    no knowledge of what the database actually looks like. As a result the only options
    would be to either define them or execute raw SQL queries and deal with the dynamic response.
  2. You added an existing database to your project in the assets folder,
    but as far as I know there is no way to perform write operations to those files at runtime.
    Instead you should copy the database to the normal storage when the application is first started.

Other than that, you should be all set to go.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top