SQLite的使用

通常在大型系统和网站一般使用的数据基本上就是Oracle,MySQL,MSSqlServer三种。但是在某些情况下会相对麻烦,如果仅仅需要在客户端保存一些数据。SQLite无疑是最佳选择之一。他是一种轻量级数据库。不用安装任何插件或者软件来辅助,只是一个简单的文件。直接打包在客户端程序内即可。

1,创建Sqlite。

     为了方便程序开发,一般把Sqlite签入Vs内部当做一个插件来使用。默认Vs是不支持Sqlite的,为了让其支持我们需要下载SQLite-1.0.66.0-setup.exe  进行安装,这时候你会发现vs的的数据源连接中多了一项:

    为了及时观察sqlite数据中数据变化,每次都打开vs连接再查看很费时间,只需要下载一个特小的软件即可轻松搞定。下载地址: SQLite Database Browser.exe    下载后解压到桌面,+98

选择此数据源。确定

点击New用来创建一个sqlite的数据库文件。  点击Browse用来打开已存在的数据库文件。

现在数据库已经创建,然后就是创建表,

右键Tables选择创建表,接下来的操作和mssqlserver基本一样。这里不具体描述。可能会在后面章节详细介绍。只能说可能会介绍,但是如何在代码中对sqlite数据操作肯定会介绍的。如果你想使用sqlite。后面的内容一定会帮到你。

2.操作数据库

  和其他数据库类似,既然要对数据库进行一系列的操作(增删改查)少不了一套方法, 和其他数据库的命令大同小异。

 下面封装的一个SqliteHelper类。

  1 using System;
  2   8 using System.Collections;
  3   9 using System.Collections.Specialized;
  4  10 using System.Data;
  5  11 using System.Data.SQLite;
  6  12 using System.Configuration;
  7  13 
  8  14 namespace Test
  9  15 {
 10  16     public class SqliteHelper
 11  17     {
 12  18         //数据库连接字符串(web.config来配置),可以动态更改SQLString支持多数据库.
 13  20         public static string connectionString = "Data Source=test";
 14  21        
 15  23         public SqliteHelper() { }
 16  24 
 17  25         #region 公用方法
 18  26 
 19  27         public static int GetMaxID(string FieldName, string TableName)
 20  28         {
 21  29             string strsql = "select max(" + FieldName + ")+1 from " + TableName;
 22  30             object obj = GetSingle(strsql);
 23  31             if (obj == null)
 24  32             {
 25  33                 return 1;
 26  34             }
 27  35             else
 28  36             {
 29  37                 return int.Parse(obj.ToString());
 30  38             }
 31  39         }
 32  40 
 33  41         public static bool Exists(string strSql)
 34  42         {
 35  43             object obj = GetSingle(strSql);
 36  44             int cmdresult;
 37  45             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
 38  46             {
 39  47                 cmdresult = 0;
 40  48             }
 41  49             else
 42  50             {
 43  51                 cmdresult = int.Parse(obj.ToString());
 44  52             }
 45  53             if (cmdresult == 0)
 46  54             {
 47  55                 return false;
 48  56             }
 49  57             else
 50  58             {
 51  59                 return true;
 52  60             }
 53  61         }
 54  62 
 55  63         public static bool Exists(string strSql, params SQLiteParameter[] cmdParms)
 56  64         {
 57  65             object obj = GetSingle(strSql, cmdParms);
 58  66             int cmdresult;
 59  67             if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
 60  68             {
 61  69                 cmdresult = 0;
 62  70             }
 63  71             else
 64  72             {
 65  73                 cmdresult = int.Parse(obj.ToString());
 66  74             }
 67  75             if (cmdresult == 0)
 68  76             {
 69  77                 return false;
 70  78             }
 71  79             else
 72  80             {
 73  81                 return true;
 74  82             }
 75  83         }
 76  84 
 77  85         #endregion
 78  86 
 79  87         #region  执行简单SQL语句
 80  88 
 81  89         /// <summary>
 82  90         /// 执行SQL语句,返回影响的记录数
 83  91         /// </summary>
 84  92         /// <param name="SQLString">SQL语句</param>
 85  93         /// <returns>影响的记录数</returns>
 86  94         public static int ExecuteSql(string SQLString)
 87  95         {
 88  96             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
 89  97             {
 90  98                 using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
 91  99                 {
 92 100                     try
 93 101                     {
 94 102                         connection.Open();
 95 103                         int rows = cmd.ExecuteNonQuery();
 96 104                         return rows;
 97 105                     }
 98 106                     catch (System.Data.SQLite.SQLiteException E)
 99 107                     {
100 108                         connection.Close();
101 109                         throw new Exception(E.Message);
102 110                     }
103 111                 }
104 112             }
105 113         }
106 114 
107 115         /// <summary>
108 116         /// 执行SQL语句,设置命令的执行等待时间
109 117         /// </summary>
110 118         /// <param name="SQLString"></param>
111 119         /// <param name="Times"></param>
112 120         /// <returns></returns>
113 121         public static int ExecuteSqlByTime(string SQLString, int Times)
114 122         {
115 123             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
116 124             {
117 125                 using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
118 126                 {
119 127                     try
120 128                     {
121 129                         connection.Open();
122 130                         cmd.CommandTimeout = Times;
123 131                         int rows = cmd.ExecuteNonQuery();
124 132                         return rows;
125 133                     }
126 134                     catch (System.Data.SQLite.SQLiteException E)
127 135                     {
128 136                         connection.Close();
129 137                         throw new Exception(E.Message);
130 138                     }
131 139                 }
132 140             }
133 141         }
134 142 
135 143         /// <summary>
136 144         /// 执行多条SQL语句,实现数据库事务。
137 145         /// </summary>
138 146         /// <param name="SQLStringList">多条SQL语句</param>        
139 147         public static void ExecuteSqlTran(ArrayList SQLStringList)
140 148         {
141 149             using (SQLiteConnection conn = new SQLiteConnection(connectionString))
142 150             {
143 151                 conn.Open();
144 152                 SQLiteCommand cmd = new SQLiteCommand();
145 153                 cmd.Connection = conn;
146 154                 SQLiteTransaction tx = conn.BeginTransaction();
147 155                 cmd.Transaction = tx;
148 156                 try
149 157                 {
150 158                     for (int n = 0; n < SQLStringList.Count; n++)
151 159                     {
152 160                         string strsql = SQLStringList[n].ToString();
153 161                         if (strsql.Trim().Length > 1)
154 162                         {
155 163                             cmd.CommandText = strsql;
156 164                             cmd.ExecuteNonQuery();
157 165                         }
158 166                     }
159 167                     tx.Commit();
160 168                 }
161 169                 catch (System.Data.SQLite.SQLiteException E)
162 170                 {
163 171                     tx.Rollback();
164 172                     throw new Exception(E.Message);
165 173                 }
166 174             }
167 175         }
168 176 
169 177         /// <summary>
170 178         /// 执行带一个存储过程参数的的SQL语句。
171 179         /// </summary>
172 180         /// <param name="SQLString">SQL语句</param>
173 181         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
174 182         /// <returns>影响的记录数</returns>
175 183         public static int ExecuteSql(string SQLString, string content)
176 184         {
177 185             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
178 186             {
179 187                 SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
180 188                 SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
181 189                 myParameter.Value = content;
182 190                 cmd.Parameters.Add(myParameter);
183 191                 try
184 192                 {
185 193                     connection.Open();
186 194                     int rows = cmd.ExecuteNonQuery();
187 195                     return rows;
188 196                 }
189 197                 catch (System.Data.SQLite.SQLiteException E)
190 198                 {
191 199                     throw new Exception(E.Message);
192 200                 }
193 201                 finally
194 202                 {
195 203                     cmd.Dispose();
196 204                     connection.Close();
197 205                 }
198 206             }
199 207         }
200 208 
201 209         /// <summary>
202 210         /// 执行带一个存储过程参数的的SQL语句。
203 211         /// </summary>
204 212         /// <param name="SQLString">SQL语句</param>
205 213         /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
206 214         /// <returns>影响的记录数</returns>
207 215         public static object ExecuteSqlGet(string SQLString, string content)
208 216         {
209 217             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
210 218             {
211 219                 SQLiteCommand cmd = new SQLiteCommand(SQLString, connection);
212 220                 SQLiteParameter myParameter = new SQLiteParameter("@content", DbType.String);
213 221                 myParameter.Value = content;
214 222                 cmd.Parameters.Add(myParameter);
215 223                 try
216 224                 {
217 225                     connection.Open();
218 226                     object obj = cmd.ExecuteScalar();
219 227                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
220 228                     {
221 229                         return null;
222 230                     }
223 231                     else
224 232                     {
225 233                         return obj;
226 234                     }
227 235                 }
228 236                 catch (System.Data.SQLite.SQLiteException E)
229 237                 {
230 238                     throw new Exception(E.Message);
231 239                 }
232 240                 finally
233 241                 {
234 242                     cmd.Dispose();
235 243                     connection.Close();
236 244                 }
237 245             }
238 246         }
239 247 
240 248         /// <summary>
241 249         /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
242 250         /// </summary>
243 251         /// <param name="strSQL">SQL语句</param>
244 252         /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
245 253         /// <returns>影响的记录数</returns>
246 254         public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
247 255         {
248 256             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
249 257             {
250 258                 SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
251 259                 SQLiteParameter myParameter = new SQLiteParameter("@fs", DbType.Binary);
252 260                 myParameter.Value = fs;
253 261                 cmd.Parameters.Add(myParameter);
254 262                 try
255 263                 {
256 264                     connection.Open();
257 265                     int rows = cmd.ExecuteNonQuery();
258 266                     return rows;
259 267                 }
260 268                 catch (System.Data.SQLite.SQLiteException E)
261 269                 {
262 270                     throw new Exception(E.Message);
263 271                 }
264 272                 finally
265 273                 {
266 274                     cmd.Dispose();
267 275                     connection.Close();
268 276                 }
269 277             }
270 278         }
271 279 
272 280         /// <summary>
273 281         /// 执行一条计算查询结果语句,返回查询结果(object)。
274 282         /// </summary>
275 283         /// <param name="SQLString">计算查询结果语句</param>
276 284         /// <returns>查询结果(object)</returns>
277 285         public static object GetSingle(string SQLString)
278 286         {
279 287             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
280 288             {
281 289                 using (SQLiteCommand cmd = new SQLiteCommand(SQLString, connection))
282 290                 {
283 291                     try
284 292                     {
285 293                         connection.Open();
286 294                         object obj = cmd.ExecuteScalar();
287 295                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
288 296                         {
289 297                             return null;
290 298                         }
291 299                         else
292 300                         {
293 301                             return obj;
294 302                         }
295 303                     }
296 304                     catch (System.Data.SQLite.SQLiteException e)
297 305                     {
298 306                         connection.Close();
299 307                         throw new Exception(e.Message);
300 308                     }
301 309                 }
302 310             }
303 311         }
304 312 
305 313         /// <summary>
306 314         /// 执行查询语句,返回SQLiteDataReader(使用该方法切记要手工关闭SQLiteDataReader和连接)
307 315         /// </summary>
308 316         /// <param name="strSQL">查询语句</param>
309 317         /// <returns>SQLiteDataReader</returns>
310 318         public static SQLiteDataReader ExecuteReader(string strSQL)
311 319         {
312 320             SQLiteConnection connection = new SQLiteConnection(connectionString);
313 321             SQLiteCommand cmd = new SQLiteCommand(strSQL, connection);
314 322             try
315 323             {
316 324                 connection.Open();
317 325                 SQLiteDataReader myReader = cmd.ExecuteReader();
318 326                 return myReader;
319 327             }
320 328             catch (System.Data.SQLite.SQLiteException e)
321 329             {
322 330                 throw new Exception(e.Message);
323 331             }
324 332             //finally //不能在此关闭,否则,返回的对象将无法使用
325 333             //{
326 334             //    cmd.Dispose();
327 335             //    connection.Close();
328 336             //}    
329 337         }
330 338 
331 339         /// <summary>
332 340         /// 执行查询语句,返回DataSet
333 341         /// </summary>
334 342         /// <param name="SQLString">查询语句</param>
335 343         /// <returns>DataSet</returns>
336 344         public static DataSet Query(string SQLString)
337 345         {
338 346             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
339 347             {
340 348                 DataSet ds = new DataSet();
341 349                 try
342 350                 {
343 351                     connection.Open();
344 352                     SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
345 353                     command.Fill(ds, "ds");
346 354                 }
347 355                 catch (System.Data.SQLite.SQLiteException ex)
348 356                 {
349 357                     throw new Exception(ex.Message);
350 358                 }
351 359                 return ds;
352 360             }
353 361         }
354 362 
355 363         public static DataSet Query(string SQLString, string TableName)
356 364         {
357 365             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
358 366             {
359 367                 DataSet ds = new DataSet();
360 368                 try
361 369                 {
362 370                     connection.Open();
363 371                     SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
364 372                     command.Fill(ds, TableName);
365 373                 }
366 374                 catch (System.Data.SQLite.SQLiteException ex)
367 375                 {
368 376                     throw new Exception(ex.Message);
369 377                 }
370 378                 return ds;
371 379             }
372 380         }
373 381 
374 382         /// <summary>
375 383         /// 执行查询语句,返回DataSet,设置命令的执行等待时间
376 384         /// </summary>
377 385         /// <param name="SQLString"></param>
378 386         /// <param name="Times"></param>
379 387         /// <returns></returns>
380 388         public static DataSet Query(string SQLString, int Times)
381 389         {
382 390             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
383 391             {
384 392                 DataSet ds = new DataSet();
385 393                 try
386 394                 {
387 395                     connection.Open();
388 396                     SQLiteDataAdapter command = new SQLiteDataAdapter(SQLString, connection);
389 397                     command.SelectCommand.CommandTimeout = Times;
390 398                     command.Fill(ds, "ds");
391 399                 }
392 400                 catch (System.Data.SQLite.SQLiteException ex)
393 401                 {
394 402                     throw new Exception(ex.Message);
395 403                 }
396 404                 return ds;
397 405             }
398 406         }
399 407 
400 408         #endregion
401 409 
402 410         #region 执行带参数的SQL语句
403 411 
404 412         /// <summary>
405 413         /// 执行SQL语句,返回影响的记录数
406 414         /// </summary>
407 415         /// <param name="SQLString">SQL语句</param>
408 416         /// <returns>影响的记录数</returns>
409 417         public static int ExecuteSql(string SQLString, params SQLiteParameter[] cmdParms)
410 418         {
411 419             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
412 420             {
413 421                 using (SQLiteCommand cmd = new SQLiteCommand())
414 422                 {
415 423                     try
416 424                     {
417 425                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);
418 426                         int rows = cmd.ExecuteNonQuery();
419 427                         cmd.Parameters.Clear();
420 428                         return rows;
421 429                     }
422 430                     catch (System.Data.SQLite.SQLiteException E)
423 431                     {
424 432                         throw new Exception(E.Message);
425 433                     }
426 434                 }
427 435             }
428 436         }
429 437 
430 438         /// <summary>
431 439         /// 执行多条SQL语句,实现数据库事务。
432 440         /// </summary>
433 441         /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的SQLiteParameter[])</param>
434 442         public static void ExecuteSqlTran(Hashtable SQLStringList)
435 443         {
436 444             using (SQLiteConnection conn = new SQLiteConnection(connectionString))
437 445             {
438 446                 conn.Open();
439 447                 using (SQLiteTransaction trans = conn.BeginTransaction())
440 448                 {
441 449                     SQLiteCommand cmd = new SQLiteCommand();
442 450                     try
443 451                     {
444 452                         //循环
445 453                         foreach (DictionaryEntry myDE in SQLStringList)
446 454                         {
447 455                             string cmdText = myDE.Key.ToString();
448 456                             SQLiteParameter[] cmdParms = (SQLiteParameter[])myDE.Value;
449 457                             PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
450 458                             int val = cmd.ExecuteNonQuery();
451 459                             cmd.Parameters.Clear();
452 460 
453 461                             trans.Commit();
454 462                         }
455 463                     }
456 464                     catch
457 465                     {
458 466                         trans.Rollback();
459 467                         throw;
460 468                     }
461 469                 }
462 470             }
463 471         }
464 472 
465 473         /// <summary>
466 474         /// 执行一条计算查询结果语句,返回查询结果(object)。
467 475         /// </summary>
468 476         /// <param name="SQLString">计算查询结果语句</param>
469 477         /// <returns>查询结果(object)</returns>
470 478         public static object GetSingle(string SQLString, params SQLiteParameter[] cmdParms)
471 479         {
472 480             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
473 481             {
474 482                 using (SQLiteCommand cmd = new SQLiteCommand())
475 483                 {
476 484                     try
477 485                     {
478 486                         PrepareCommand(cmd, connection, null, SQLString, cmdParms);
479 487                         object obj = cmd.ExecuteScalar();
480 488                         cmd.Parameters.Clear();
481 489                         if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
482 490                         {
483 491                             return null;
484 492                         }
485 493                         else
486 494                         {
487 495                             return obj;
488 496                         }
489 497                     }
490 498                     catch (System.Data.SQLite.SQLiteException e)
491 499                     {
492 500                         throw new Exception(e.Message);
493 501                     }
494 502                 }
495 503             }
496 504         }
497 505 
498 506         /// <summary>
499 507         /// 执行查询语句,返回SQLiteDataReader (使用该方法切记要手工关闭SQLiteDataReader和连接)
500 508         /// </summary>
501 509         /// <param name="strSQL">查询语句</param>
502 510         /// <returns>SQLiteDataReader</returns>
503 511         public static SQLiteDataReader ExecuteReader(string SQLString, params SQLiteParameter[] cmdParms)
504 512         {
505 513             SQLiteConnection connection = new SQLiteConnection(connectionString);
506 514             SQLiteCommand cmd = new SQLiteCommand();
507 515             try
508 516             {
509 517                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
510 518                 SQLiteDataReader myReader = cmd.ExecuteReader();
511 519                 cmd.Parameters.Clear();
512 520                 return myReader;
513 521             }
514 522             catch (System.Data.SQLite.SQLiteException e)
515 523             {
516 524                 throw new Exception(e.Message);
517 525             }
518 526             //finally //不能在此关闭,否则,返回的对象将无法使用
519 527             //{
520 528             //    cmd.Dispose();
521 529             //    connection.Close();
522 530             //}    
523 531 
524 532         }
525 533 
526 534         /// <summary>
527 535         /// 执行查询语句,返回DataSet
528 536         /// </summary>
529 537         /// <param name="SQLString">查询语句</param>
530 538         /// <returns>DataSet</returns>
531 539         public static DataSet Query(string SQLString, params SQLiteParameter[] cmdParms)
532 540         {
533 541             using (SQLiteConnection connection = new SQLiteConnection(connectionString))
534 542             {
535 543                 SQLiteCommand cmd = new SQLiteCommand();
536 544                 PrepareCommand(cmd, connection, null, SQLString, cmdParms);
537 545                 using (SQLiteDataAdapter da = new SQLiteDataAdapter(cmd))
538 546                 {
539 547                     DataSet ds = new DataSet();
540 548                     try
541 549                     {
542 550                         da.Fill(ds, "ds");
543 551                         cmd.Parameters.Clear();
544 552                     }
545 553                     catch (System.Data.SQLite.SQLiteException ex)
546 554                     {
547 555                         throw new Exception(ex.Message);
548 556                     }
549 557                     return ds;
550 558                 }
551 559             }
552 560         }
553 561 
554 562         public static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, SQLiteTransaction trans, string cmdText, SQLiteParameter[] cmdParms)
555 563         {
556 564             if (conn.State != ConnectionState.Open)
557 565                 conn.Open();
558 566             cmd.Connection = conn;
559 567             cmd.CommandText = cmdText;
560 568             if (trans != null)
561 569                 cmd.Transaction = trans;
562 570             cmd.CommandType = CommandType.Text;//cmdType;
563 571             if (cmdParms != null)
564 572             {
565 573 
566 574 
567 575                 foreach (SQLiteParameter parameter in cmdParms)
568 576                 {
569 577                     if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
570 578                         (parameter.Value == null))
571 579                     {
572 580                         parameter.Value = DBNull.Value;
573 581                     }
574 582                     cmd.Parameters.Add(parameter);
575 583                 }
576 584             }
577 585         }
578 586 
579 587         #endregion
580 588 
581 589         #region 参数转换
582 590         /// <summary>
583 591         /// 放回一个SQLiteParameter
584 592         /// </summary>
585 593         /// <param name="name">参数名字</param>
586 594         /// <param name="type">参数类型</param>
587 595         /// <param name="size">参数大小</param>
588 596         /// <param name="value">参数值</param>
589 597         /// <returns>SQLiteParameter的值</returns>
590 598         public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, int size, object value)
591 599         {
592 600             SQLiteParameter parm = new SQLiteParameter(name, type, size);
593 601             parm.Value = value;
594 602             return parm;
595 603         }
596 604 
597 605         public static SQLiteParameter MakeSQLiteParameter(string name, DbType type, object value)
598 606         {
599 607             SQLiteParameter parm = new SQLiteParameter(name, type);
600 608             parm.Value = value;
601 609             return parm;
602 610         }
603 611 
604 612         #endregion
605 613     }
606 614 }
View Code

通过这个基本满足对sqlite的操作。

  

 

 

 

 

posted @ 2013-07-19 12:38  Mountains  阅读(450)  评论(0编辑  收藏  举报