Xamarin SQLite数据库为所有表创建

时间:2016-07-25 13:46:33

标签: sql xamarin

我已经在这个主题上工作了4个小时,但我无法得到任何解决方案。

我的问题其实是; 我有5个表,我想创建一个控制器来创建不同的表。

我目前的代码如下,但此代码只创建一个表格。

public interface ISQLite
{
    SQLiteConnection GetConnection();
}

-

public class TodoItem
{
    public TodoItem ()
    {
    }

    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Notes { get; set; }
    public bool Done { get; set; }
}

-

public class TodoItemDatabase 
{
    static object locker = new object ();

    SQLiteConnection database;

    /// <summary>
    /// Initializes a new instance of the <see cref="Tasky.DL.TaskDatabase"/> TaskDatabase. 
    /// if the database doesn't exist, it will create the database and all the tables.
    /// </summary>
    /// <param name='path'>
    /// Path.
    /// </param>
    public TodoItemDatabase()
    {
        database = DependencyService.Get<ISQLite> ().GetConnection ();
        // create the tables
        database.CreateTable<TodoItem>();
    }

    public IEnumerable<TodoItem> GetItems ()
    {
        lock (locker) {
            return (from i in database.Table<TodoItem>() select i).ToList();
        }
    }

    public IEnumerable<TodoItem> GetItemsNotDone ()
    {
        lock (locker) {
            return database.Query<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
        }
    }

    public TodoItem GetItem (int id) 
    {
        lock (locker) {
            return database.Table<TodoItem>().FirstOrDefault(x => x.ID == id);
        }
    }

    public int SaveItem (TodoItem item) 
    {
        lock (locker) {
            if (item.ID != 0) {
                database.Update(item);
                return item.ID;
            } else {
                return database.Insert(item);
            }
        }
    }

    public int DeleteItem(int id)
    {
        lock (locker) {
            return database.Delete<TodoItem>(id);
        }
    }
}

-

public class SQLite_Android : ISQLite
{
    public SQLite_Android()
    {
    }

    #region ISQLite implementation
    public SQLite.SQLiteConnection GetConnection()
    {
        var sqliteFilename = "TodoSQLite.db3";
        string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, sqliteFilename);

        // This is where we copy in the prepopulated database
        Console.WriteLine(path);
        if (!File.Exists(path))
        {
            var s = Forms.Context.Resources.OpenRawResource(Resource.Raw.TodoSQLite);  // RESOURCE NAME ###

            // create a write stream
            FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            // write to the stream
            ReadWriteStream(s, writeStream);
        }

        var conn = new SQLite.SQLiteConnection(path);

        // Return the database connection 
        return conn;
    }
    #endregion

    /// <summary>
    /// helper method to get the database out of /raw/ and into the user filesystem
    /// </summary>
    void ReadWriteStream(Stream readStream, Stream writeStream)
    {
        int Length = 256;
        Byte[] buffer = new Byte[Length];
        int bytesRead = readStream.Read(buffer, 0, Length);
        // write the required bytes
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = readStream.Read(buffer, 0, Length);
        }
        readStream.Close();
        writeStream.Close();
    }
}

---如何在一个控制器中创建多个表?

2 个答案:

答案 0 :(得分:1)

看起来你正在使用Sqlite.net-pcl,对吧?

不支持来自同一型号的多个表(仅适用于简单的情况)。

您可以创建多个模型(可能只是继承),然后为每个模型调用CreatTable<T>

答案 1 :(得分:1)

我解决了问题。也许这个解决方案有助于某些人。

我有两个DbHepler Class和两个用于在DB上创建两个表的模型类。

基本连接代码相同;

public interface ISQLite
{
    SQLiteConnection GetConnection();
}

这是App.cs文件;

public class App : Application {
    public App()
    {
        authenticationDB = new AuthenticationDbHelper(Database);
        settingsDbHelper = new SettingsDbHelper(Database);
        MainPage = new Views.MainMenuPage();
    }
public static CreateDB Database
    {
        get
        {
            if (database == null)
            {
                database = new CreateDB();
            }
            return database;
        }
    }
}

CreateDB类是为所有表创建一个数据库所必需的

public class CreateDB
{
    public SQLiteConnection database;
    public object locker = new object();
    public CreateDB()
    {
        database = DependencyService.Get<ISQLite>().GetConnection();
    }

}

此接口是创建的表操作所必需的。自从实现这个类以来我们可以使用theese方法所有表。(T是表类)(要了解一下AuthenticationDBHelper类)

public interface SQLiteBase<T>
{
    IEnumerable<T> GetItems();
    T GetItem(long id);
    long SaveItem(T item);
    void UpdateItem(T item);
    int DeleteItem(int id);
    int Clear();
    int getCount();
}

此DbHelper类将用于删除,插入,清除....项目。

public class AuthenticationDbHelper : SQLiteBase<AuthenticationDbTable>
{
    SQLiteConnection database;
    object locker;
    public AuthenticationDbHelper(CreateDB db)
    {
        database = db.database;
        locker = db.locker;
        database.CreateTable<AuthenticationDbTable>();
    }

    public int Clear()
    {
        lock(locker)
        {
            return database.DeleteAll<AuthenticationDbTable>();
        }
    }

    public int DeleteItem(int id)
    {
        lock (locker)
        {
            return database.Delete<AuthenticationDbTable>(id);
        }
    }

    public AuthenticationDbTable GetItem(long id)
    {
        lock (locker)
        {
            return database.Table<AuthenticationDbTable>().FirstOrDefault(x => x.UserId == id);
        }
    }

    public IEnumerable<AuthenticationDbTable> GetItems()
    {
        lock (locker)
        {
            return (from i in database.Table<AuthenticationDbTable>() select i).ToList();
        }
    }

    public long SaveItem(AuthenticationDbTable item)
    {
        lock (locker)
        {
             return database.Insert(item);
        }
    }

    public void UpdateItem(AuthenticationDbTable item)
    {
        lock(locker)
        {
            database.Update(item);
        }
    }

    public int getCount()
    {
        return GetItems().Count();
    }

}

我知道这很困惑,但这是最后一次。我们将创建用于身份验证的模型。

public class AuthenticationDbTable
{

    public AuthenticationDbTable(long userId, string sessionId, string username, string clientuuid)
    {
        this.userId = userId;
        this.sessionId = sessionId;
        this.username = username;
        this.clientuuid = clientuuid;
    }


    private long userId;
    private string sessionId;
    private string username;
    private string clientuuid;

    [PrimaryKey]
    public long UserId
    {
        get { return userId; }
        set { userId = value; }
    }

    public string SessionId
    {
        get { return sessionId; }
        set { sessionId = value; }
    }

    public string Username
    {
        get { return username; }
        set { username = value; }
    }

    public string Clientuuid
    {
        get { return clientuuid; }
        set { clientuuid = value; }
    }
}

AuthenticationDbTable authentication = new AuthenticationDbTable(authenticateduser.User.UserId, r.Retval.SessionStatus.SessionId, authenticateduser.User.Name, authenticateduser.Clientuuid);
App.authenticationDB.SaveItem(authentiaction);

注意

要创建第二个表,您可以使用相同的方法。您应该创建第二个DbHelper和模型类。假设您将为设置创建一个表。您应该创建SettingsDbHelper和SettingsDbTable类。通过相同的方式。

谢谢:)