在.NET C#中使用SQLite

本文介绍了SQLite数据库的基本特性,包括其轻量级、跨平台和支持事务处理等优点,并提供了使用.NET进行SQLite操作的示例代码。
      小型数据库中推荐大家使用SQLite,在中小型软件、网站开发时,如果不需要对数据管理有太高的要求都可以采用SQLite,其最关键的一点是免费而且开源。像Adobe Reader,Firefox中都采用了SQLite。官方网站 http://www.sqlite.org/ ,当前版本是3.6.17。
一、SQLite基本特性
  • 支持事务处理。
  • 零配置。
  • 支持大部分SQL92标准。
  • 数据库存储在单个文件中。
  • 默认支持十亿字节长的字符串。
  • SQLite解释器小于300kb。
  • 比C/S型的数据库更快。
  • 简单便捷的API。
  • 采用ANSI-C 编译,同时支持多种语言。
  • 完全开源,完全免费。
  • 跨平台。
  • 自包含,不需要任何第三方组件。

     SQLite 不支持以下SQL特性:
     FOREIGN KEY constraints,Complete trigger support,Complete ALTER TABLE support, RIGHT and FULL OUTER JOIN,
     Writing to ViEWs,GRANT and REVOKE。

二、GUI管理工具
     在SQLite的Wiki 上列出了很多管理工具,参见 http://www.sqlite.org/cvstrac/wiki?p=ManagementTools ,推荐大家使用SQLite2009 Pro,
下载见 http://osenxpsuite.net/?xp=3 ,也是免费的,最新版本的SQLite引擎是3.6.16。使用起来也很方便。
     主界面如下:


三、.NET的Wrapper
        很多语言都提供了SQLite 的Wrapper,见 http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers
        推荐使用SQLite.NET,官方网站 http://sqlite.phxsoftware.com/ ,SourceForge项目主页 http://sourceforge.net/projects/sqlite-dotnet2/
SQLite.NET 还支持LINQ方式调用。同时提供VS插件,可以在VS中直接编辑数据库。
        最后,附上包装SQLite 的C#代码用于举例怎么使用。
  1 using  System;
  2 using  System.Collections.Generic;
  3 using  System.Linq;
  4 using  System.Text;
  5 using  System.Data;
  6 using  System.Data.SQLite;
  7
  8 namespace  AirLibrary
  9 ExpandedBlockStart.gifContractedBlock.gif {
 10ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 11    /// 数据库接口类
 12    /// </summary>

 13    public class SQLite : IDisposable
 14ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 15ContractedSubBlock.gifExpandedSubBlockStart.gif        Attribute#region Attribute
 16        private string datasource = @"db\data.db3";
 17        private bool isOpen;
 18        private bool disposed = false;
 19
 20        private SQLiteConnection connection;
 21        private Dictionary<stringstring> parameters;
 22        #endregion
 //Attribute
 23
 24ContractedSubBlock.gifExpandedSubBlockStart.gif        Constructor#region Constructor
 25        public SQLite()
 26ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 27            init("");
 28        }

 29
 30ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 31        /// 连接指定的数据库
 32        /// </summary>
 33        /// <param name="datasource">连接字符串</param>

 34        public SQLite(string datasource)
 35ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 36            init(datasource);
 37        }

 38
 39ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 40        /// 清理托管资源
 41        /// </summary>

 42        public void Dispose()
 43ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 44            Dispose(true);
 45            GC.SuppressFinalize(this);
 46        }

 47
 48ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 49        /// 清理所有使用资源
 50        /// </summary>
 51        /// <param name="disposing">如果为true则清理托管资源</param>

 52        protected void Dispose(bool disposing)
 53ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 54            if (!this.disposed)
 55ExpandedSubBlockStart.gifContractedSubBlock.gif            {
 56                // dispose all managed resources.
 57                if (disposing)
 58ExpandedSubBlockStart.gifContractedSubBlock.gif                {
 59                    this.isOpen = false;
 60                    connection.Dispose();
 61                }

 62
 63                // dispose all unmanaged resources
 64                this.close();
 65
 66                disposed = true;
 67            }

 68        }

 69
 70        ~SQLite()
 71ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 72            Dispose(false);
 73        }

 74        #endregion
 //Constructor
 75
 76ContractedSubBlock.gifExpandedSubBlockStart.gif        Function#region Function
 77        private void init(string datasource)
 78ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 79            if (datasource != "")
 80                this.datasource = datasource;
 81            this.connection = new SQLiteConnection("data source = " + this.datasource);
 82            this.parameters = new Dictionary<stringstring>();
 83            this.isOpen = false;
 84        }

 85
 86        private bool checkDbExist()
 87ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 88            if (System.IO.File.Exists(datasource))
 89                return true;
 90            else
 91                return false;
 92        }

 93
 94        private void open()
 95ExpandedSubBlockStart.gifContractedSubBlock.gif        {
 96            if (!checkDbExist())
 97                throw new AirException("1001");
 98
 99            if (!isOpen)
100                connection.Open();
101
102            this.isOpen = true;
103        }

104
105        private void close()
106ExpandedSubBlockStart.gifContractedSubBlock.gif        {
107            if (isOpen)
108                connection.Close();
109
110            this.isOpen = false;
111        }

112        #endregion
 //Function
113
114ContractedSubBlock.gifExpandedSubBlockStart.gif        Method#region Method
115ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
116        /// 添加参数
117        /// </summary>
118        /// <param name="key">参数名</param>
119        /// <param name="value">参数值</param>

120        public void AddParameter(string key, string value)
121ExpandedSubBlockStart.gifContractedSubBlock.gif        {
122            parameters.Add(key, value);
123        }

124
125ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
126        /// 执行SQL语句
127        /// </summary>
128        /// <param name="queryStr">SQL语句</param>

129        public void ExecuteNonQuery(string queryStr)
130ExpandedSubBlockStart.gifContractedSubBlock.gif        {
131            this.open();
132            using (SQLiteTransaction transaction = connection.BeginTransaction())
133ExpandedSubBlockStart.gifContractedSubBlock.gif            {
134                using (SQLiteCommand command = new SQLiteCommand(connection))
135ExpandedSubBlockStart.gifContractedSubBlock.gif                {
136                    command.CommandText = queryStr;
137                    foreach (KeyValuePair<stringstring> kvp in this.parameters)
138ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
139                        command.Parameters.Add(new SQLiteParameter(kvp.Key, kvp.Value));
140                    }

141
142                    command.ExecuteNonQuery();
143                }

144                transaction.Commit();
145            }

146            this.close();
147            this.parameters.Clear();            
148        }

149
150ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
151        /// 执行SQL语句并返回所有结果
152        /// </summary>
153        /// <param name="queryStr">SQL语句</param>
154        /// <returns>返回DataTable</returns>

155        public DataTable ExecuteQuery(string queryStr)
156ExpandedSubBlockStart.gifContractedSubBlock.gif        {
157            DataTable dt = new DataTable();
158            this.open();
159            try
160ExpandedSubBlockStart.gifContractedSubBlock.gif            {
161                using (SQLiteCommand command = new SQLiteCommand(connection))
162ExpandedSubBlockStart.gifContractedSubBlock.gif                {
163                    SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
164                    command.CommandText = queryStr;
165                    foreach (KeyValuePair<stringstring> kvp in this.parameters)
166ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
167                        command.Parameters.Add(new SQLiteParameter(kvp.Key, kvp.Value));
168                    }

169
170                    adapter.Fill(dt);
171                }

172            }

173            catch (SQLiteException e)
174ExpandedSubBlockStart.gifContractedSubBlock.gif            {
175                throw new AirException("1002", e.Message);
176            }

177            finally
178ExpandedSubBlockStart.gifContractedSubBlock.gif            {
179                this.close();
180                this.parameters.Clear();
181            }

182            return dt;
183        }

184
185ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
186        /// 执行SQL语句并返回第一行
187        /// </summary>
188        /// <param name="queryStr">SQL语句</param>
189        /// <returns>返回DataRow</returns>

190        public DataRow ExecuteRow(string queryStr)
191ExpandedSubBlockStart.gifContractedSubBlock.gif        {
192            DataRow row;
193            this.open();
194            try
195ExpandedSubBlockStart.gifContractedSubBlock.gif            {
196                using (SQLiteCommand command = new SQLiteCommand(connection))
197ExpandedSubBlockStart.gifContractedSubBlock.gif                {
198                    SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
199                    command.CommandText = queryStr;
200                    foreach (KeyValuePair<stringstring> kvp in this.parameters)
201ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
202                        command.Parameters.Add(new SQLiteParameter(kvp.Key, kvp.Value));
203                    }

204
205                    DataTable dt = new DataTable();
206                    adapter.Fill(dt);
207                    if (dt.Rows.Count == 0)
208                        row = null;
209                    else
210                        row = dt.Rows[0];
211                }

212            }

213            catch (SQLiteException e)
214ExpandedSubBlockStart.gifContractedSubBlock.gif            {
215                throw new AirException("1002", e.Message);
216            }

217            finally
218ExpandedSubBlockStart.gifContractedSubBlock.gif            {
219                this.close();
220                this.parameters.Clear();
221            }

222            return row;
223        }

224
225ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
226        /// 执行SQL语句并返回结果第一行的第一列
227        /// </summary>
228        /// <param name="queryStr">SQL语句</param>
229        /// <returns>返回值</returns>

230        public Object ExecuteScalar(string queryStr)
231ExpandedSubBlockStart.gifContractedSubBlock.gif        {
232            Object obj;
233            this.open();
234            using (SQLiteCommand command = new SQLiteCommand(connection))
235ExpandedSubBlockStart.gifContractedSubBlock.gif            {
236                command.CommandText = queryStr;
237                foreach (KeyValuePair<stringstring> kvp in this.parameters)
238ExpandedSubBlockStart.gifContractedSubBlock.gif                {
239                    command.Parameters.Add(new SQLiteParameter(kvp.Key, kvp.Value));
240                }

241
242                obj = command.ExecuteScalar();
243            }

244            this.close();
245            this.parameters.Clear();
246            return obj;
247        }

248        #endregion
 //Method
249    }

250}

251

         这里的异常类是我自己项目中用的,大家实际使用时换成自己的异常类就是了。这里只是SQLite的一些简单应用,欢迎大家讨论指点。

转载于:https://www.cnblogs.com/robertzml/archive/2009/08/27/1554874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值