当前位置:Gxlcms > 数据库问题 > C# SQLite 创建数据库的方法增删查改语法和命令

C# SQLite 创建数据库的方法增删查改语法和命令

时间:2021-07-01 10:21:17 帮助过:13人阅读

 

SQLite是一个开源、免费的小型RDBMS(关系型数据库),能独立运行、无服务器、零配置、支持事物,用C实现,内存占用较小,支持绝大数的SQL92标准。

SQLite数据库官方主页:http://www.sqlite.org/index.html

 

cmd下sqlite的使用网

 

1:选择下载对应自己系统的sqlite.3exe文件

 

2:解压后使用cmd命令进入sqlite3.exe文件所在的路径执行命令就可以操作做相应的操作。

在进入数据库之后如果需要退出的话windows下摁ctrl+c就能退出

例如:

创建数据库命令:sqlite3.exe 【数据库名字.后缀名】

 

  这里比较牛一点的感觉就是创建的数据库后缀名是任意的、不过注意一点就是:在命令框下执行创建数据库的时候。

 

如果没有为数据库创建表格、则看不见数据库文件,所以必须创建表格。

 

  例如:在CMD命令提示符下输入sqlite3.exe test.db(test.db是数据库名)回车,执行完后,命令提示符自动跳转

 

到"SQLITE>"状态。这时还是看不到这个数据库!等表格创建或关闭sqlite3

 

例如:create table user(’用户名‘); 这时可以看到sqlite3.exe所在文件夹下的这个数据库文件了

 

如果下次还要使用此数据库时仍然使用sqlite3.exe test.db即可进入此数据库 

 

基础命令(增删改查)

创建表格命令:create table tablename(字段,字段) 

这里从命令上可以清楚的看到、在sqlite数据库中创建表格字段的时候、允许不为字段申明数据类型。 

这是区别于其它关系型数据库的。 

执行插入命令:insert into tablename values(value,values)

在、前面我们可以看出、sqlite的操作上和sqlserver没什么太大区别、值得注意的是、insert时区别于sqlserver中、因为sqlserver中允许使用 "insert table  name values(value,value)"这样的省略式擦入。但是sqlite中是不允许使用省略式插入语句的。 

执行删除语句:delete  from tablename where <条件> 

删除数据语法和sqlserver相同、 

删除表则命令为:drop table tablename 

数据更新命令:update tablename set 字段=值 如果需要条件的话、添加上where语句。 

执行查询语句:select *from tablename 可跟随where语句

 

以上就是基础的sqlite的增删查改语法和命令。 

 

C#操作SQLite Database

C#下SQLite操作驱动dll下载:System.Data.SQLite

C#使用SQLite步骤:

(1)新建一个project

(2)添加SQLite dll引用(操作驱动)

(3)使用API操作SQLite DataBase

操作SQLite Database的C#帮助类SQLite Helper

技术分享
 1 using System;
 2 using System.Data.SQLite;
 3  
 4 namespace SQLiteSamples
 5 {
 6     class Program
 7     {
 8         //数据库连接
 9         SQLiteConnection m_dbConnection;
10  
11         static void Main(string[] args)
12         {
13             Program p = new Program();
14         }
15  
16         public Program()
17         {
18             createNewDatabase();
19             connectToDatabase();
20             createTable();
21             fillTable();
22             printHighscores();
23         }
24  
25         //创建一个空的数据库
26         void createNewDatabase()
27         {
28             SQLiteConnection.CreateFile("MyDatabase.sqlite");
29         }
30  
31         //创建一个连接到指定数据库
32         void connectToDatabase()
33         {
34             m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
35             m_dbConnection.Open();
36         }
37  
38         //在指定数据库中创建一个table
39         void createTable()
40         {
41             string sql = "create table highscores (name varchar(20), score int)";
42             SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
43             command.ExecuteNonQuery();
44         }
45  
46         //插入一些数据
47         void fillTable()
48         {
49             string sql = "insert into highscores (name, score) values (‘Me‘, 3000)";
50             SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
51             command.ExecuteNonQuery();
52  
53             sql = "insert into highscores (name, score) values (‘Myself‘, 6000)";
54             command = new SQLiteCommand(sql, m_dbConnection);
55             command.ExecuteNonQuery();
56  
57             sql = "insert into highscores (name, score) values (‘And I‘, 9001)";
58             command = new SQLiteCommand(sql, m_dbConnection);
59             command.ExecuteNonQuery();
60         }
61  
62         //使用sql查询语句,并显示结果
63         void printHighscores()
64         {
65             string sql = "select * from highscores order by score desc";
66             SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
67             SQLiteDataReader reader = command.ExecuteReader();
68             while (reader.Read())
69                 Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);
70             Console.ReadLine();
71         }
72     }
73 }
View Code

 

SQLite Helper类

将一些常用的功能封装一下,封装成SQLite Helper类

技术分享
  1 using System;
  2 using System.Data;
  3 using System.Text.RegularExpressions;
  4 using System.Xml;
  5 using System.IO;
  6 using System.Collections;
  7 using System.Data.SQLite;
  8  
  9 namespace DBUtility.SQLite
 10 {
 11     /// <summary>
 12     /// SQLiteHelper is a utility class similar to "SQLHelper" in MS
 13     /// Data Access Application Block and follows similar pattern.
 14     /// </summary>
 15     public class SQLiteHelper
 16     {
 17         /// <summary>
 18         /// Creates a new <see cref="SQLiteHelper"/> instance. The ctor is marked private since all members are static.
 19         /// </summary>
 20         private SQLiteHelper()
 21         {
 22         }
 23         /// <summary>
 24         /// Creates the command.
 25         /// </summary>
 26         /// <param name="connection">Connection.</param>
 27         /// <param name="commandText">Command text.</param>
 28         /// <param name="commandParameters">Command parameters.</param>
 29         /// <returns>SQLite Command</returns>
 30         public static SQLiteCommand CreateCommand(SQLiteConnection connection, string commandText, params SQLiteParameter[] commandParameters)
 31         {
 32             SQLiteCommand cmd = new SQLiteCommand(commandText, connection);
 33             if (commandParameters.Length > 0)
 34             {
 35                 foreach (SQLiteParameter parm in commandParameters)
 36                     cmd.Parameters.Add(parm);
 37             }
 38             return cmd;
 39         }
 40  
 41         /// <summary>
 42         /// Creates the command.
 43         /// </summary>
 44         /// <param name="connectionString">Connection string.</param>
 45         /// <param name="commandText">Command text.</param>
 46         /// <param name="commandParameters">Command parameters.</param>
 47         /// <returns>SQLite Command</returns>
 48         public static SQLiteCommand CreateCommand(string connectionString, string commandText, params SQLiteParameter[] commandParameters)
 49         {
 50             SQLiteConnection cn = new SQLiteConnection(connectionString);
 51  
 52             SQLiteCommand cmd = new SQLiteCommand(commandText, cn);
 53  
 54             if (commandParameters.Length > 0)
 55             {
 56                 foreach (SQLiteParameter parm in commandParameters)
 57                     cmd.Parameters.Add(parm);
 58             }
 59             return cmd;
 60         }
 61         /// <summary>
 62         /// Creates the parameter.
 63         /// </summary>
 64         /// <param name="parameterName">Name of the parameter.</param>
 65         /// <param name="parameterType">Parameter type.</param>
 66         /// <param name="parameterValue">Parameter value.</param>
 67         /// <returns>SQLiteParameter</returns>
 68         public static SQLiteParameter CreateParameter(string parameterName, System.Data.DbType parameterType, object parameterValue)
 69         {
 70             SQLiteParameter parameter = new SQLiteParameter();
 71             parameter.DbType = parameterType;
 72             parameter.ParameterName = parameterName;
 73             parameter.Value = parameterValue;
 74             return parameter;
 75         }
 76  
 77         /// <summary>
 78         /// Shortcut method to execute dataset from SQL Statement and object[] arrray of parameter values
 79         /// </summary>
 80         /// <param name="connectionString">SQLite Connection string</param>
 81         /// <param name="commandText">SQL Statement with embedded "@param" style parameter names</param>
 82         /// <param name="paramList">object[] array of parameter values</param>
 83         /// <returns></returns>
 84         public static DataSet ExecuteDataSet(string connectionString, string commandText, object[] paramList)
 85         {
 86             SQLiteConnection cn = new SQLiteConnection(connectionString);
 87             SQLiteCommand cmd = cn.CreateCommand();
 88  
 89  
 90             cmd.CommandText = commandText;
 91             if (paramList != null)
 92             {
 93                 AttachParameters(cmd,commandText, paramList);
 94             }
 95             DataSet ds = new DataSet();
 96             if (cn.State == ConnectionState.Closed)
 97                 cn.Open();
 98             SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
 99             da.Fill(ds);
100             da.Dispose();
101             cmd.Dispose();
102             cn.Close();
103             return ds;
104         }
105         /// <summary>
106         /// Shortcut method to execute dataset from SQL Statement and object[] arrray of  parameter values
107         /// </summary>
108         /// <param name="cn">Connection.</param>
109         /// <param name="commandText">Command text.</param>
110         /// <param name="paramList">Param list.</param>
111         /// <returns></returns>
112         public static DataSet ExecuteDataSet(SQLiteConnection cn, string commandText, object[] paramList)
113         {
114  
115             SQLiteCommand cmd = cn.CreateCommand();
116  
117  
118             cmd.CommandText = commandText;
119             if (paramList != null)
120             {
121                 AttachParameters(cmd,commandText, paramList);
122             }
123             DataSet ds = new DataSet();
124             if (cn.State == ConnectionState.Closed)
125                 cn.Open();
126             SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
127             da.Fill(ds);
128             da.Dispose();
129             cmd.Dispose();
130             cn.Close();
131             return ds;
132         }
133         /// <summary>
134         /// Executes the dataset from a populated Command object.
135         /// </summary>
136         /// <param name="cmd">Fully populated SQLiteCommand</param>
137         /// <returns>DataSet</returns>
138         public static DataSet ExecuteDataset(SQLiteCommand cmd)
139         {
140             if (cmd.Connection.State == ConnectionState.Closed)
141                 cmd.Connection.Open();
142             DataSet ds = new DataSet();
143             SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
144             da.Fill(ds);
145             da.Dispose();
146             cmd.Connection.Close();
147             cmd.Dispose();
148             return ds;
149         }
150  
151         /// <summary>
152         /// Executes the dataset in a SQLite Transaction
153         /// </summary>
154         /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction,  /// and Command, all of which must be created prior to making this method call. </param>
155         /// <param name="commandText">Command text.</param>
156         /// <param name="commandParameters">Sqlite Command parameters.</param>
157         /// <returns>DataSet</returns>
158         /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
159         public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, params SQLiteParameter[] commandParameters)
160         {
161  
162             if (transaction == null) throw new ArgumentNullException("transaction");
163             if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed, please provide an open transaction.", "transaction");
164             IDbCommand cmd = transaction.Connection.CreateCommand();
165             cmd.CommandText = commandText;
166             foreach (SQLiteParameter parm in commandParameters)
167             {
168                 cmd.Parameters.Add(parm);
169             }
170             if (transaction.Connection.State == ConnectionState.Closed)
171                 transaction.Connection.Open();
172             DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
173             return ds;
174         }
175  
176         /// <summary>
177         /// Executes the dataset with Transaction and object array of parameter values.
178         /// </summary>
179         /// <param name="transaction">SQLiteTransaction. Transaction consists of Connection, Transaction,    /// and Command, all of which must be created prior to making this method call. </param>
180         /// <param name="commandText">Command text.</param>
181         /// <param name="commandParameters">object[] array of parameter values.</param>
182         /// <returns>DataSet</returns>
183         /// <remarks>user must examine Transaction Object and handle transaction.connection .Close, etc.</remarks>
184         public static DataSet ExecuteDataset(SQLiteTransaction transaction, string commandText, object[] commandParameters)
185         {
186  
187             if (transaction == null) throw new ArgumentNullException("transaction");
188             if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rolled back or committed,                                                          please provide an open transaction.", "transaction");
189             IDbCommand cmd = transaction.Connection.CreateCommand();
190             cmd.CommandText = commandText;
191             AttachParameters((SQLiteCommand)cmd,cmd.CommandText, commandParameters);
192             if (transaction.Connection.State == ConnectionState.Closed)
193                 transaction.Connection.Open();
194  
195             DataSet ds = ExecuteDataset((SQLiteCommand)cmd);
196             return ds;
197         }
198  
199         #region UpdateDataset
200         /// <summary>
201         /// Executes the respective command for each inserted, updated, or deleted row in the DataSet.
202         /// </summary>
203         /// <remarks>
204         /// e.g.: 
205         ///  UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order");
206         /// </remarks>
207         /// <param name="insertCommand">A valid SQL statement  to insert new records into the data source</param>
208         /// <param name="deleteCommand">A valid SQL statement to delete records from the data source</param>
209         /// <param name="updateCommand">A valid SQL statement used to update records in the data source</param>
210         /// <param name="dataSet">The DataSet used to update the data source</param>
211         /// 
                        
                    

人气教程排行