热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#sqliteforwp7

Published: 10Mar2011By: XianzhongZhu DownloadSampleCodeInthisarticleIwillintroducetoyouane

Published: 10 Mar 2011
By: Xianzhong Zhu 
《C# sqlite for wp7》Download Sample Code

In this article I will introduce to you a new, strong and easy-to-use native database solution, called Sqlite Client for Windows Phone, provided by CodePlex, together with other associated programming tips.

Welcome Google Searcher!

I noticed that you arrived here from Google looking for QLiteCommand.ExecuteQuery() . The below article is probably best suited for you based on the provided keywords.

 

If the information provided on this page is not helpful, please consider posting in our forums or in the comment section of this page. Registration takes less than 30 seconds.

 

Contents [hide]
  • 1 Introduction
  • 2 Introduction to Sqlite Client for Windows Phone
    • 2.1 Infrastructure in Sqlite Client for Windows Phone
  • 3 Using SQLite Manager to Simplify Database Management
  • 4 A Useful Utility Class – DBHelper
  • 5 A Simple Customer Editor
    • 5.1 Running-time screenshots
    • 5.2 Behind implementation
  • 6 Summary

 

Introduction

Either from a user’s perspective or from a developer’s perspective, Windows Phone 7 has brought us dozens of new and exciting features. At the same time, there are also numerous missing features in the current Windows Phone 7 Series expected by various kinds of users. One of the representative regrets may be lacking local database API – the current Windows Phone 7 OS only supports access to data via XML, Isolated Storage, and Cloud Storage. Do we really have no other choice? Not necessarily so. Luckily there are several developers and teams have been working to fill this gap.

Note although there have been several efforts to create Windows Phone 7 databases, in the end, these all run on top of isolated storage. In this article I will introduce to you a new, strong and easy-to-use native database solution, called Sqlite Client for Windows Phone, provided by CodePlex, together with other associated programming tips.

NOTE

The sample test environments in this article involve:

1. Windows 7;

2. .NET 4.0;

3. Visual Studio 2010;

4. Windows Phone Developer Tools RTW;

5. Sqlite Client for Windows Phone (http://sqlitewindowsphone.codeplex.com/);

6. (Optional) sqlite-manager (http://code.google.com/p/sqlite-manager/);

7. (Optional) MVVM Light Toolkit (http://mvvmlight.codeplex.com/).

Introduction to Sqlite Client for Windows Phone

As is well-known, SQLite is a famous open sourced embedded database system, already supported on iOS and Android. Thanks to at least Dan Ciprian Ardelean, we can now move those same files into our WP7 versions via C#-SQLite! Recently, Dan has put a renewed, stronger and easier-to-use solution, named Sqlite Client for Windows Phone, on CodePlex at http://sqlitewindowsphone.codeplex.com/releases.

Figure 1: Download Sqlite Client for Windows Phone

《C# sqlite for wp7》

Sqlite Client for Windows Phone has made some great updates with Booleans, Blobs, and transactions, based upon the old C#-SQLite. And also, it provides a good sample included in the download.

Figure 2: Sqlite Client for Windows Phone and the sample project

《C# sqlite for wp7》

The subsequent thing is simple: rebuild the library Community.CsharpSqlite.WP to get an assembly named Community.CsharpSqlite.WP.dll (the release version size is 525KB), add related reference in your WP7 Silverlight project, and then put in use the functionalities.

Infrastructure in Sqlite Client for Windows Phone

If you have any SQL scripts based database experience, you can easily work with Sqlite Client for Windows Phone. Especially, built upon the former C#-SQLite project, it further simplifies the basic database and table related operations by introducing a few helper classes (in the file SQLiteClient.cs), such as SQLiteException, SQLiteConnection, and SQLiteCommand. Figures 3, 4, and 5 illustrate the main components and associated relationships in Sqlite Client for Windows Phone.

Figure 3: The topmost components in Sqlite Client for Windows Phone

《C# sqlite for wp7》

Figure 4: The main components inside SQLiteConnection

《C# sqlite for wp7》

Figure 5: The main components inside SQLiteCommand

《C# sqlite for wp7》

Before using Sqlite Client for Windows Phone, it’s necessary to introduce another useful tool named sqlite-manager (http://code.google.com/p/sqlite-manager/). Since we have to deal with a lot of Sqlite related stuff, some readers may query: how can we create Sqlite databases, tables, views, and more? Just take it easy; all these can be accomplished via sqlite-manager, a famous Firefox add-on.

Using SQLite Manager to Simplify Database Management

SQLite Manager is a FireFox add-on, which can be easily retrieved and installed using FireFox’s add-on manager (Figure 6).

Figure 6: Retrieve SQLite Manager and install it in FireFox

《C# sqlite for wp7》

As indicated in Figure 5, if you open up the add-on explorer in FireFox and enter “sqlite manager” in the textbox and start searching you will easily retrieve this add-on. Then you can click the button “Add to Firefox…” to start to download and install SQLite Manager. Note, as hinted later in Firefox, you should restart Firefox to finish the installation.

Using SQLite Manager is easy. This is the first time I meet SQLite Manager; I find it mighty and pretty easy to start with. If you ever used VB6, you might be familiar with the built-in database manager – VisData with which to create small Access database. To be honest, it was not easy to use, but at that time we felt well. Now you bear in mind SQLite Manager is better than VISDATA 1,000 times.

Figure 7: The experience of SQLite Manager is cool

《C# sqlite for wp7》

You can use SQLite Manager to deal with nearly all kinds of SQLite related things. To learn SQLite related concepts and syntaxes, you can use the Help menu to get a quick guide.

OK, in this article related sample project, I created one table named Customer in a database named database1.sqlite.

Figure 8: Schema for table Customer

《C# sqlite for wp7》

After creating database1.sqlite, copy/move it to the sample project (WP7SQLiteClient) root folder. Then set its Build Action property to Resource. The reason to do this is relevant to the following handling with this file. You can of course choose Content, but you should resort to other related solutions.

A Useful Utility Class – DBHelper

As indicated above, Sqlite Client for Windows Phone has provided a high-level encapsulation around the common database operations using the widely-known SQL statements. To deal with the SQLite database in Silverlight for Windows Phone 7, we can use the objects defined in the file SQLiteClient.cs (in the source library project) directly, i.e. SQLiteException, SQLiteConnection, and SQLiteCommand.

Although Sqlite Client for Windows Phone does not interact with Isolated Storage directly, to add support for Isolated Storage is necessary to improve the system performance. Hence, we can further encapsulate the SQLiteClient objects mentioned previously. For this, Chris has brought a good utility class called DBHelper. To be used in our case, I’ve made a slight modification with it.

Listing 1: The modified utility class DBHelper

001.
//others omitted...
002.
using SQLiteClient;
003.
using System.Linq;
004.
using System.IO.IsolatedStorage;
005.
using System.Collections.Generic;
006.
using System.Collections.ObjectModel;
007.
namespace WP7SQLiteClient.Helpers
008.
{
009.
public class DBHelper
010.
{
011.
private String _dbName;
012.
private SQLiteConnection db = null;
013.
public DBHelper(String assemblyName, String dbName)
014.
{
015.
IsolatedStorageFile store =IsolatedStorageFile.GetUserStoreForApplication();
016.
if (!store.FileExists(dbName))
017.
{
018.
CopyFromContentToStorage(assemblyName, dbName);
019.
}
020.
_dbName = dbName;
021.
}
022.
~DBHelper()
023.
{
024.
Close();
025.
}
026.
private void Open()
027.
{
028.
if (db == null)
029.
{
030.
db = new SQLiteConnection(_dbName);
031.
db.Open();
032.
}
033.
}
034.
private void Close()
035.
{
036.
if (db != null)
037.
{
038.
db.Dispose();
039.
db = null;
040.
}
041.
}
042.
//Insert operation
043.
public int Insert(T obj, string statement) where T : new()
044.
{
045.
try
046.
{
047.
Open();
048.
SQLiteCommand cmd = db.CreateCommand(statement);
049.
int rec = cmd.ExecuteNonQuery(obj);
050.
return rec;
051.
}
052.
catch (SQLiteException ex)
053.
{
054.
System.Diagnostics.Debug.WriteLine("Insert failed: " + ex.Message);
055.
throw ex;
056.
}
057.
}
058.
// Delete operation
059.
public void Delete(string statement) where T : new()
060.
{
061.
try
062.
{
063.
Open();
064.
SQLiteCommand cmd = db.CreateCommand(statement);
065.
cmd.ExecuteNonQuery();
066.
}
067.
catch (SQLiteException ex)
068.
{
069.
System.Diagnostics.Debug.WriteLine("Deletion failed: " + ex.Message);
070.
throw ex;
071.
}
072.
}
073.
//Query operation
074.
public List SelectList(String statement) where T : new()
075.
{
076.
Open();
077.
SQLiteCommand cmd = db.CreateCommand(statement);
078.
var lst = cmd.ExecuteQuery();
079.
return lst.ToList();
080.
}
081.
public ObservableCollection SelectObservableCollection(String statement)
082.
where T : new()
083.
{
084.
List lst = SelectList(statement);
085.
ObservableCollection oc = new ObservableCollection();
086.
foreach (T item in lst)
087.
{
088.
oc.Add(item);
089.
}
090.
return oc;
091.
}
092.
private void CopyFromContentToStorage(String assemblyName,String dbName)
093.
{
094.
IsolatedStorageFile store =
095.
IsolatedStorageFile.GetUserStoreForApplication();
096.
System.IO.Stream src =
097.
Application.GetResourceStream(
098.
new Uri("/" + assemblyName + ";component/" + dbName,
099.
UriKind.Relative)).Stream;
100.
IsolatedStorageFileStream dest =
101.
new IsolatedStorageFileStream(dbName,
102.
System.IO.FileMode.OpenOrCreate,
103.
System.IO.FileAccess.Write, store);
104.
src.Position = 0;
105.
CopyStream(src, dest);
106.
dest.Flush();
107.
dest.Close();
108.
src.Close();
109.
dest.Dispose();
110.
}
111.
private static void CopyStream(System.IO.Stream input,
112.
IsolatedStorageFileStream output)
113.
{
114.
byte[] buffer = new byte[32768];
115.
long TempPos = input.Position;
116.
int readCount;
117.
do
118.
{
119.
readCount = input.Read(buffer, 0, buffer.Length);
120.
if (readCount > 0)
121.
{
122.
output.Write(buffer, 0, readCount);
123.
}
124.
while (readCount > 0);
125.
input.Position = TempPos;
126.
}
127.
}
128.
}

By the way, I’ve not also performed optimization with the above helper. Hope readers to continue with this work according to your related job. Simply put, I’ve mainly added the Insert and Delete methods. The most outstanding feature in the above code is the method CopyFromContentToStorage, with which we achieved the preceding target – setting up relations with Isolated Storage.

Following up the above routine, you can continue to extend the previous DBHelper class, including more typical and helpful CRUD operations and other more detailed table manipulations, as well as full optimization. Next, we’ll construct a simple customer editor using the above stuff.

A Simple Customer Editor

Start up Visual Studio 2010 to create a simple Windows Phone 6 application WP7SQLiteClient. Then, open the solution and add a reference to the assembly Community.CsharpSqlite.WP.dll (from the bin directory of the compiled Sqlite Client for Windows Phone project).

Running-time screenshots

To gain a better understanding with the following explanation, let’s first look at the running-time snapshots, as shown in Figures 9 and 10.

Figure 9: The initial screenshot of the customer editor

《C# sqlite for wp7》

Note in the initial screenshot of the customer editor there are only three records which have been populated using Sqlite Manager. When you click the button “Add” five customers will be added at the table Customer. In this sample, I’ve not refresh the screen immediately. However, if you press the hardware Back button (we’ve used the emulator) and navigate back to this screen again you will see the five newly-appended records, as shown in Figure 10.

Figure 10: Five sample customer records added to the table Customer

《C# sqlite for wp7》

Now, press the button “Del Last 1” in Figure 10, the last record will be removed from the table Customer in the database database1.sqlite. Figure 11 illustrates the related screenshot.

Figure 11: The last record is removed from the table Customer

《C# sqlite for wp7》

Next, let’s look into the behind implementation.

Behind implementation

First, we’d better defined a public property db in the App class, so that we can access it from every page.

01.
public partial class App : Application
02.
{
03.
private DBHelper _db;
04.
public DBHelper db
05.
{
06.
get
07.
{
08.
Assembly assem = Assembly.GetExecutingAssembly();
09.
if (_db == null)
10.
_db = new DBHelper(assem.FullName.Substring(0, assem.FullName.IndexOf(',')), "database1.sqlite");
11.
return _db;
12.
}
13.
}
14.
//...others omitted

Next, let’s put initialization in the Behind-Code file TestDataEditor.xaml.cs.

01.
//others omitted...
02.
using WP7SQLiteClient.Dal;
03.
using System.Collections.ObjectModel;//ObservableCollection
04.
using System.ComponentModel;
05.
using SQLiteClient;
06.
using Community.CsharpSqlite;
07.
using System.Collections;
08.
namespace WP7SQLiteClient
09.
{
10.
public partial class TestDataEditor : PhoneApplicationPage
11.
{
12.
ObservableCollection _customerEntries = null;
13.
public TestDataEditor()
14.
{
15.
InitializeComponent();
16.
//retrieve dat
17.
string strSelect = "SELECT ID,Name,Email,Desc FROM Customer ORDER BY ID ASC";
18.
_customerEntries = (Application.Current as App).db.SelectObservableCollection(strSelect);
19.
foreach (Customer data in _customerEntries)
20.
{
21.
TextBlockID.Text += data.ID + Environment.NewLine;
22.
TextBlockName.Text +=data.Name + Environment.NewLine;
23.
TextBlockEmail.Text +=data.Email + Environment.NewLine;
24.
TextBlockDesc.Text +=data.Desc + Environment.NewLine;
25.
}
26.
}
27.
//others omitted...

In the above code, we first defined a variable _customerEntries of type ObservableCollection. Then, in the constructor we built up a standard SQL SELECT string. Next, by invoking the method SelectObservableCollection defined in the DBHelper class related instance in the global App class, all customer data have been retrieved into the variable _customerEntries. At last, by iterating through the collection structure, we succeeded in displaying all customer data onto the screen.

1. Adding records

Now, let’s check out how to add the five sample customer data into the table Customer.

01.
private void btnAdd_Click(object sender, RoutedEventArgs e)
02.
{
03.
DateTime start = DateTime.Now;
04.
int rec;
05.
Random rnd = new Random();
06.
string strInsert = " Insert into Customer (Name,Email,Desc) values (@Name,@Email,@Desc)";
07.
for (int i = 0; i <5; i++)
08.
{
09.
Customer tst = new Customer
10.
{
11.
Name = "Name " + i,
12.
Email = Name + "@" "#.com",
13.
Desc = "Desc for " + i
14.
};
15.
rec = (Application.Current as App).db.Insert (tst,strInsert);
16.
}
17.
System.Diagnostics.Debug.WriteLine("\nInserted 5 " " rows\r\nGenerated in " + (DateTime.Now - start).TotalSeconds);
18.
}

As is seen, with the help of the helper class DBHelper, the retrieving and insert operations with SQLite database seem quite similar to those in desktop-styled relational database systems – easy to write and follow up.

2. Deleting records

Deletion operation is even easier, as shown in Listing 5 below.

1.
private void btnDel_Click(object sender, RoutedEventArgs e)
2.
{
3.
DateTime start = DateTime.Now;
4.
string strDel = " Delete from Customer where ID=""(SELECT COUNT(*) FROM Customer)" ;
5.
(Application.Current as App).db.Delete(strDel);
6.
}

In the above code, the last record in the table Customer will be removed. Obviously, to write complex and fully-functional SQL statements you should first know the SQLite database related syntaxes very well. In fact, this is not difficult – there have already tons of tutorials concerning SQLite (for example at http://www.sqlite.org/lang.html).

Summary

In this article we&#8217;ve brought to you a mighty an


推荐阅读
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文讨论了Kotlin中扩展函数的一些惯用用法以及其合理性。作者认为在某些情况下,定义扩展函数没有意义,但官方的编码约定支持这种方式。文章还介绍了在类之外定义扩展函数的具体用法,并讨论了避免使用扩展函数的边缘情况。作者提出了对于扩展函数的合理性的质疑,并给出了自己的反驳。最后,文章强调了在编写Kotlin代码时可以自由地使用扩展函数的重要性。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • VScode格式化文档换行或不换行的设置方法
    本文介绍了在VScode中设置格式化文档换行或不换行的方法,包括使用插件和修改settings.json文件的内容。详细步骤为:找到settings.json文件,将其中的代码替换为指定的代码。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文详细介绍了在ASP.NET中获取插入记录的ID的几种方法,包括使用SCOPE_IDENTITY()和IDENT_CURRENT()函数,以及通过ExecuteReader方法执行SQL语句获取ID的步骤。同时,还提供了使用这些方法的示例代码和注意事项。对于需要获取表中最后一个插入操作所产生的ID或马上使用刚插入的新记录ID的开发者来说,本文提供了一些有用的技巧和建议。 ... [详细]
author-avatar
动感奥13
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有