用C#访问SQLite入门(1)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
⽤C#访问SQLite⼊门(1)
⽤ C# 访问 SQLite ⼊门 (1)
SQLite 在 VS C# 环境下的开发,⽹上已经有很多教程。
我也是从这些教程开始学习的。
⽽要专门写下这⼀篇,是因为按照⽹上教程的例⼦,会遇到⼀些问题,特别是⼀些细节的设置,没有具体涉及,往往就让我这样的初学者碰壁,明明是全部照搬的却不断出错⽽不知解决⽅法。
这⾥就特别记录和注明我遇到的问题和解决⽅法,让其他的初学者可以仿照处理。
这⾥⽤到的例⼦和C#语句,都是从⽹上来的。
1. 下载安装 Sqlite
安装则是按提⽰进⾏即可
2. 建⽴Sqlite 数据库⽂件
我是在 Firefox 下,安装 SQLite Manager 来建⽴的。
例如,建⽴⼀个 Books.sqlite 数据库⽂件:
从 Firefox 菜单启动 SQLite Manager,点 Database -> New Database,输⼊数据库⽂件名
然后选择保存路径,例如把⽂件保存到桌⾯。
点 Execute SQL ,在 Enter SQL 区域输⼊建库语句,如下:
Sql代码
1. CREATE TABLE Book
2. (
3. ID INTEGER,
4. BookName VARCHAR(50),
5. Price DOUBLE,
6. Rowguid VARCHAR(70),
7. PRIMARY KEY(ID)
8. )
然后点 Run SQL 即可完成建库⼯作。
在 SQLite Manager 点 Database -> Close Database,关闭数据库并退出 SQLite Manager.
新建⼀个 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类的定义:
C#代码
1. public class Book
2. {
3. private int id;
4. private string bookName;
5. private decimal price;
6. private string rowguid;
7.
8. public int ID
9. {
10. get { return id; }
11. set { id = value; }
12. }
13.
14. public string BookName
15. {
16. get { return bookName; }
17. set { bookName = value; }
18. }
19.
20. public decimal Price
21. {
22. get { return price; }
23. set { price = value; }
24. }
25.
26. public string Rowguid
27. {
28. get { return rowguid; }
29. set { rowguid = value; }
30. }
31.
32. public Book()
33. { }
34.
35. public Book(int _id, string _bookname, decimal _price, string _rowguid)
36. {
37. id = _id;
38. bookName = _bookname;
39. price = _price;
40. rowguid = _rowguid;
41. }
42. }
保存。
类似步骤,输⼊数据库操作类: BookDAL.cs
1. public class BookDAL
2. {
3. public static bool CreateBook(Book book)
4. {
5. try
6. {
7. SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;");
8. conn.Open();
9. SQLiteCommand cmd = conn.CreateCommand();
10. mandText = "INSERT INTO Book(ID, BookName, Price, Rowguid) VALUES(@ID1, @BookName1, @Price1, @Rowguid1)";
11. cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
12. cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
13. cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
14. cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
15.
16. int i = cmd.ExecuteNonQuery();
17. return i == 1;
18. }
19. catch (SQLiteException se)
20. {
21. MessageBox.Show(se.Message + " \n\n" + se.Source + "\n\n" + se.StackTrace + "\n\n" + se.Data);
22. return false;
23. }
24. catch (ArgumentException ae)
25. {
26. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace + "\n\n" + ae.Data);
27. return false;
28. }
29. catch (Exception ex)
30. {
31. //Do any logging operation here if necessary
32. MessageBox.Show(ex.Message + "\n\n" + ex.Source + "\n\n" + ex.StackTrace + "\n\n" + ex.Data);
33. return false;
34. }
35. }
36.
37. public static bool UpdateBookByID(Book book)
38. {
39. try
40. {
41. using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
42. {
43. conn.Open();
44. SQLiteCommand cmd = conn.CreateCommand();
45. mandText = "update Book set BookName=@BookName1,Price=@Price1, Rowguid=@Rowguid1 where ID=@ID1;";
46. cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
47. cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
48. cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
49. cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
50. int i = cmd.ExecuteNonQuery();
51. return i == 1;
52. }
53. }
54. catch (ArgumentException ae)
55. {
56. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
57. return false;
58. }
59. catch (Exception ex)
60. {
61. //Do any logging operation here if necessary
62. MessageBox.Show(ex.Message);
63. return false;
64. }
65. }
66.
67. public static bool UpdateBookByGuid(Book book)
68. {
69. try
70. {
71. using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
73. conn.Open();
74. SQLiteCommand cmd = conn.CreateCommand();
75. mandText = "update Book set ID=@ID1,BookName=@BookName1,Price=@Price1 where Rowguid=@Rowguid1;";
76. cmd.Parameters.Add(new SQLiteParameter("ID1", book.ID));
77. cmd.Parameters.Add(new SQLiteParameter("BookName1", book.BookName));
78. cmd.Parameters.Add(new SQLiteParameter("Price1", book.Price));
79. cmd.Parameters.Add(new SQLiteParameter("Rowguid1", book.Rowguid));
80. int i = cmd.ExecuteNonQuery();
81. return i == 1;
82. }
83. }
84. catch (ArgumentException ae)
85. {
86. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
87. return false;
88. }
89. catch (Exception ex)
90. {
91. //Do any logging operation here if necessary
92. MessageBox.Show(ex.Message);
93. return false;
94. }
95. }
96.
97. public static bool DeleteBook(int ID)
98. {
99. try
100. {
101. using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
102. {
103. conn.Open();
104. SQLiteCommand cmd = conn.CreateCommand();
105. mandText = "delete from Book where ID=@ID;";
106. cmd.Parameters.Add(new SQLiteParameter("ID", ID));
107. int i = cmd.ExecuteNonQuery();
108. return i == 1;
109. }
110. }
111. catch (ArgumentException ae)
112. {
113. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
114. return false;
115. }
116. catch (Exception ex)
117. {
118. //Do any logging operation here if necessary
119. MessageBox.Show(ex.Message);
120. return false;
121. }
122. }
123.
124. public static Book GetBookByID(int ID)
125. {
126. try
127. {
128. using (SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;"))
129. {
130. conn.Open();
131. SQLiteCommand cmd = conn.CreateCommand();
132. mandText = "select * from Book where ID=@ID;";
133. cmd.Parameters.Add(new SQLiteParameter("ID", ID));
134. SQLiteDataReader dr = cmd.ExecuteReader();
135. if (dr.Read())
136. {
137. Book book = new Book();
138. book.ID = dr.GetInt32(0);
139. book.BookName = dr.GetString(1);
140. book.Price = dr.GetDecimal(2);
141. return book;
142. }
143. else
145. }
146. }
147. catch (ArgumentException ae)
148. {
149. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace);
150. return null;
151. }
152. catch (Exception ex)
153. {
154. //Do any logging operation here if necessary
155. throw new Exception(ex.Message);
156. }
157. }
158.
159. public static DataTable GetAllBook()
160. {
161. DataTable dt = new DataTable();
162. try
163. {
164. SQLiteConnection conn = new SQLiteConnection("Data Source=db/Books.sqlite;");
165. conn.Open();
166. SQLiteCommand cmd = new SQLiteCommand(conn);
167. mandText = "SELECT * FROM Book";
168. mandType = CommandType.Text;
169. //Console.WriteLine(mandText);
170. SQLiteDataReader dr = cmd.ExecuteReader();
171. if (dr.HasRows)
172. {
173. dt.Load(dr);
174. }
175. else {
176. //throw new NullReferenceException("No Record Available.");
177. }
178.
179. dr.Close();
180. conn.Close();
181.
182. }
183. catch (ArgumentException ae)
184. {
185. MessageBox.Show(ae.Message + " \n\n" + ae.Source + "\n\n" + ae.StackTrace + "\n\n" + ae.Data); 186. }
187. catch (Exception ex)
188. {
189. //throw new Exception(ex.Message);
190. MessageBox.Show(ex.Message + " \n\n" + ex.Source + "\n\n" + ex.StackTrace + "\n\n" + ex.Data); 191. }
192.
193. return dt;
194. }
195. }
在数据库操作类,因为涉及数据库的操作,要在 using 部分,必须加⼊ using System.Data. SQLite 的引⽤等语句。
C#代码
1. using System.Data;
2. using System.Data.SQLite;
3. using System.Windows.Forms;
注意了:
错。
这个时候,就要仔细看看控制符和代码的问题。
要减少这类问题,在⽹页拷贝的代码,先粘贴到⼀个纯⽂本的编辑器,例如 Notepad++ ,然后从 Notepad++ 选择和复制,再粘贴到 VS 。
对于粘贴过来的代码,要特别注意其空格。
例如,下⾯这个就是从粘贴后的代码:
可以看到第14⾏,18⾏等的空格特别长,当移动光标的时候,它是⼀个空格!但实际上它并不是⼀个空格。
⼀旦运⾏程序,就会提⽰记录记录为空,实际上是找不到数据库⽂件,或 SQL语句错误等等。
处理的办法很简单,就是在这些语句,⼿⼯逐个把空格删掉,然后按⼀下空格键加上空格。
就可以发现⾃⼰加的空格位是⽐较⼩的,呵呵。
这些操作没有任何技术含量,但也值得分享⼀下,。