windows phone:使用sqlite-net

继上篇文章后,这里简单介绍下sqlite-net的使用(示例不为作者所写,摘自于:https://github.com/peterhuene/sqlite-net)

Please consult the Wiki for, ahem, complete documentation.

The library contains simple attributes that you can use to control the construction of tables. In a simple stock program, you might use:

public class Stock
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [MaxLength(8)]
    public string Symbol { get; set; }
}

public class Valuation
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    [Indexed]
    public int StockId { get; set; }
    public DateTime Time { get; set; }
    public decimal Price { get; set; }
}

Once you've defined the objects in your model you have a choice of APIs. You can use the "synchronous API" where calls block one at a time, or you can use the "asynchronous API" where calls do not block. You may care to use the asynchronous API for mobile applications in order to increase reponsiveness.

Both APIs are explained in the two sections below.

Synchronous API

Once you have defined your entity, you can automatically generate tables in your database by calling CreateTable:

var db = new SQLiteConnection("foofoo");
db.CreateTable<Stock>();
db.CreateTable<Valuation>();

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

public static void AddStock(SQLiteConnection db, string symbol) {
    var s = db.Insert(new Stock() {
        Symbol = symbol
    });
    Console.WriteLine("{0} == {1}", s.Symbol, s.Id);
}

Similar methods exist for Update and Delete.

The most straightforward way to query for data is using the Table method. This can take predicates for constraining via WHERE clauses and/or adding ORDER BY clauses:

    var conn = new SQLiteConnection("foofoo");
    var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));

    foreach (var stock in query)
        Debug.WriteLine("Stock: " + stock.Symbol);

You can also query the database at a low-level using the Query method:

public static IEnumerable<Valuation> QueryValuations (SQLiteConnection db, Stock stock)
{
    return db.Query<Valuation> ("select * from Valuation where StockId = ?", stock.Id);
}

The generic parameter to the Query method specifies the type of object to create for each row. It can be one of your table classes, or any other class whose public properties match the column returned by the query. For instance, we could rewrite the above query as:

public class Val {
    public decimal Money { get; set; }
    public DateTime Date { get; set; }
}
public static IEnumerable<Val> QueryVals (SQLiteConnection db, Stock stock)
{
    return db.Query<Val> ("select 'Price' as 'Money', 'Time' as 'Date' from Valuation where StockId = ?", stock.Id);
}

You can perform low-level updates of the database using the Execute method.

Asynchronous API

The asynchronous library uses the Task Parallel Library (TPL). As such, normal use of Task objects, and the async and await keywords will work for you.

Once you have defined your entity, you can automatically generate tables by calling CreateTableAsync:

var conn = new SQLiteAsyncConnection("foofoo");
conn.CreateTableAsync<Stock>().ContinueWith((results) =>
{
    Debug.WriteLine("Table created!");
});

You can insert rows in the database using Insert. If the table contains an auto-incremented primary key, then the value for that key will be available to you after the insert:

    Stock stock = new Stock()
    {
        Symbol = "AAPL"
    };

    var conn = new SQLiteAsyncConnection("foofoo");
    conn.InsertAsync(stock).ContinueWith((t) =>
    {
        Debug.WriteLine("New customer ID: {0}", stock.Id);
    });

Similar methods exist for UpdateAsync and DeleteAsync.

Querying for data is most straightforwardly done using the Table method. This will return an AsyncTableQuery instance back, whereupon you can add predictates for constraining via WHERE clauses and/or adding ORDER BY. The database is not physically touched until one of the special retrieval methods - ToListAsync, FirstAsync, or FirstOrDefaultAsync - is called.

    var conn = new SQLiteAsyncConnection("foofoo");
    var query = conn.Table<Stock>().Where(v => v.Symbol.StartsWith("A"));

    query.ToListAsync().ContinueWith((t) =>
    {
        foreach (var stock in t.Result)
            Debug.WriteLine("Stock: " + stock.Symbol);
    });

There are a number of low-level methods available. You can also query the database directly via the QueryAsync method. Over and above the change operations provided by InsertAsync etc you can issue ExecuteAsync methods to change sets of data directly within the database.

Another helpful method is ExecuteScalarAsync. This allows you to return a scalar value from the database easily:

    var conn = new SQLiteAsyncConnection("foofoo");
    conn.ExecuteScalarAsync<int>("select count(*) from Stock", null).ContinueWith((t) =>
    {
        Debug.WriteLine(string.Format("Found '{0}' stock items.", t.Result));
    });

Special note on use within Windows Store Apps (Windows 8/WinRT)

sqlite-net is fully compliant with WinRT Metro-style apps and will pass Microsoft Store validation.

Please note:

  • Database files will always be created in the path returned by Windows.Storage.ApplicationData.Current.LocalFolder.Path.

  • You will need a copy of sqlite3.dll for your app as well. You can get this from sqlite.org with an installer to the SQLite for Windows Runtime SDK.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值