原文:http://kingsz1.iteye.com/blog/1109156
用 C# 访问 SQLite 入门 (1)
SQLite 在 VS C# 环境下的开发,网上已经有很多教程。我也是从这些教程开始学习的。而要专门写下这一篇,是因为按照网上教程的例子,会遇到一些问题,特别是一些细节的设置,没有具体涉及,往往就让我这样的初学者碰壁,明明是全部照搬的却不断出错而不知解决方法。这里就特别记录和注明我遇到的问题和解决方法,让其他的初学者可以仿照处理。
这里用到的例子和C#语句,都是从网上来的。
1. 下载安装 Sqlite ADO.NET
可以从 sourceforge 下载: http://sourceforge.net/projects/sqlite-dotnet2/
安装则是按提示进行即可
2. 建立Sqlite 数据库文件
我是在 Firefox 下,安装 SQLite Manager 来建立的。例如,建立一个 Books.sqlite 数据库文件:
从 Firefox 菜单 启动 SQLite Manager, 点 Database -> New Database, 输入数据库文件名
然后选择保存路径,例如 把文件保存到 桌面。
点 Execute SQL , 在 Enter SQL 区域 输入建库语句,如下:
- CREATE TABLE Book
- (
- ID INTEGER,
- BookName VARCHAR(50),
- Price DOUBLE,
- Rowguid VARCHAR(70),
- PRIMARY KEY(ID)
- )
然后点 Run SQL 即可完成建库工作。
在 SQLite Manager 点 Database -> Close Database, 关闭数据库并退出 SQLite Manager.
3. 新建 C# Project, 引用 sqlite
新建一个 VC# 的 Windows Form Application, 命名为 dg2 (或其他名)。
在 VS 菜单, 点 Project -> Add Reference
在 .NET 下找到 System.Data.SQLite, 点 OK.
注意了,重点步骤:
在 VS 的右边,Soultion Explor , References, 点 System.Data.SQLite
然后, 在下面的 Properties 的 Copy Local, 选 True
这一步很重要,如果没有这个设置,以后在Debug 或 Build 后试运行,会提示找不到 System.Data.SQLite
4. 加入数据库文件
把数据库文件放到一个目录下。先建目录:
在右边的 Solution Explorer, 在Project名字上点鼠标右键,
在弹出选项,选 Add -> New Folder
然后,给 New Folder 改个名字, 例如 db
把数据库文件加入到这个 db 目录之下。
在 db 目录名上 点鼠标右键,在弹出菜单 选 Add -> Existing Item
然后,在打开的文件对话框,找到以前建立的数据库文件。如上面所示的例子,新建的 Books.sqlite 数据库文件是放在 桌面,我们就从桌面找到和选中这个文件,点 Add,即可把这个文件加入 db 目录下。
点一下 这个数据库文件,在下面的 Properties 选项 Copy to output Directory , 必须选 Copy always
注意: 这个设置很重要。否则就找不到数据库文件。
5. 建立相关类文件 Class
在 VS 菜单, 点 Project -> Add Class, 给个名字 Book.cs , 点 Add, 然后输入对 Book类 的定义:
- public class Book
- {
- private int id;
- private string bookName;
- private decimal price;
- private string rowguid;
- public int ID
- {
- get { return id; }
- set { id = value; }
- }
- public string BookName
- {
- get { return bookName; }
- set { bookName = value; }
- }
- public decimal Price
- {
- get { return price; }
- set { price = value; }
- }
- public string Rowguid
- {
- get { return rowguid; }
- set { rowguid = value; }
- }
- public Book()
- { }
- public Book(int _id, string _bookname, decimal _price, string _rowguid)
- {
- id = _id;
- bookName = _bookname;
- price = _price;
- rowguid = _rowguid;
- }
- }
保存。
类似步骤,输入 数据库操作类: BookDAL.cs
- public class BookDAL
- {
- public static bool CreateBook(Book book)
- {
- try
- {
- SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;");
- conn.Open();
- SQLiteCommand cmd = conn.CreateCommand();
- cmd.CommandText = "INSERT INTO Book(ID, BookName, Price, Rowguid) VALUES(@ID1, @BookName1, @Price1, @Rowguid1)";
- cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
- cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
- cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
- cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
- int i = cmd.ExecuteNonQuery();
- return i == 1;
- }
- catch (SQLiteException se)
- {
- MessageBox.Show(se.Message + " \n\n" + se.Source + "\n\n" + se.StackTrace + "\n\n" + se.Data);
- return false;
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace + "\n\n" + ae.Data);
- return false;
- }
- catch (Exception ex)
- {
- //Do any logging operation here if necessary
- MessageBox.Show(ex.Message + "\n\n" + ex.Source + "\n\n" + ex.StackTrace + "\n\n" + ex.Data);
- return false;
- }
- }
- public static bool UpdateBookByID(Book book)
- {
- try
- {
- using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
- {
- conn.Open();
- SQLiteCommand cmd = conn.CreateCommand();
- cmd.CommandText = "update Book set BookName=@BookName1,Price=@Price1, Rowguid=@Rowguid1 where ID=@ID1;";
- cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
- cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
- cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
- cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
- int i = cmd.ExecuteNonQuery();
- return i == 1;
- }
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
- return false;
- }
- catch (Exception ex)
- {
- //Do any logging operation here if necessary
- MessageBox.Show(ex.Message);
- return false;
- }
- }
- public static bool UpdateBookByGuid(Book book)
- {
- try
- {
- using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
- {
- conn.Open();
- SQLiteCommand cmd = conn.CreateCommand();
- cmd.CommandText = "update Book set ID=@ID1,BookName=@BookName1,Price=@Price1 where Rowguid=@Rowguid1;";
- cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
- cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
- cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
- cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
- int i = cmd.ExecuteNonQuery();
- return i == 1;
- }
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
- return false;
- }
- catch (Exception ex)
- {
- //Do any logging operation here if necessary
- MessageBox.Show(ex.Message);
- return false;
- }
- }
- public static bool DeleteBook(int ID)
- {
- try
- {
- using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
- {
- conn.Open();
- SQLiteCommand cmd = conn.CreateCommand();
- cmd.CommandText = "delete from Book where ID=@ID;";
- cmd.Parameters.Add(new SQLiteParameter("ID", ID));
- int i = cmd.ExecuteNonQuery();
- return i == 1;
- }
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
- return false;
- }
- catch (Exception ex)
- {
- //Do any logging operation here if necessary
- MessageBox.Show(ex.Message);
- return false;
- }
- }
- public static Book GetBookByID(int ID)
- {
- try
- {
- using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
- {
- conn.Open();
- SQLiteCommand cmd = conn.CreateCommand();
- cmd.CommandText = "select * from Book where ID=@ID;";
- cmd.Parameters.Add(new SQLiteParameter("ID", ID));
- SQLiteDataReader dr = cmd.ExecuteReader();
- if (dr.Read())
- {
- Book book = new Book();
- book.ID = dr.GetInt32(0);
- book.BookName = dr.GetString(1);
- book.Price = dr.GetDecimal(2);
- return book;
- }
- else
- return null;
- }
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
- return null;
- }
- catch (Exception ex)
- {
- //Do any logging operation here if necessary
- throw new Exception(ex.Message);
- }
- }
- public static DataTable GetAllBook()
- {
- DataTable dt = new DataTable();
- try
- {
- SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;");
- conn.Open();
- SQLiteCommand cmd = new SQLiteCommand(conn);
- cmd.CommandText = "SELECT * FROM Book";
- cmd.CommandType = CommandType.Text;
- //Console.WriteLine(cmd.CommandText);
- SQLiteDataReader dr = cmd.ExecuteReader();
- if (dr.HasRows)
- {
- dt.Load(dr);
- }
- else {
- //throw new NullReferenceException("No Record Available.");
- }
- dr.Close();
- conn.Close();
- }
- catch (ArgumentException ae)
- {
- MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace + "\n\n" + ae.Data);
- }
- catch (Exception ex)
- {
- //throw new Exception(ex.Message);
- MessageBox.Show(ex.Message + " \n\n" + ex.Source + "\n\n" + ex.StackTrace + "\n\n" + ex.Data);
- }
- return dt;
- }
- }
在数据库操作类,因为涉及数据库的操作,要在 using 部分,必须加入 using System.Data. SQLite 的引用等语句。
- using System.Data;
- using System.Data.SQLite;
- using System.Windows.Forms;
注意了:
初学者都喜欢用别人的代码来做练习,拷贝过来,粘贴上去,可减少敲键盘的时间。但是,在网页上拷贝代码,然后贴到 VS里,会引起很多问题。例如 html 的控制符,空格等等,导致以后程序运行出错,而且不知道错误在哪里。明明在屏幕上看到人家的代码 与 你的代码是一样的,但就是出错。这个时候,就要仔细看看控制符和代码的问题。
要减少这类问题,在网页拷贝的代码, 先粘贴到一个纯文本的编辑器,例如 Notepad++ , 然后从 Notepad++ 选择和复制, 再粘贴到 VS 。
对于粘贴过来的代码,要特别注意其空格。例如, 下面这个就是从粘贴后的代码:
可以看到 第14行,18行 等的 空格特别长,当移动光标的时候,它是一个 空格!但实际上它并不是一个空格。一旦运行程序,就会提示记录记录为空,实际上是找不到 数据库文件,或 SQL语句错误等等。
处理的办法很简单, 就是在这些语句,手工逐个把空格删掉,然后按一下空格键加上空格。就可以发现自己加的空格位是比较小的,呵呵。
这些操作没有任何技术含量,但也值得分享一下,