C#操作Sqlite实例

C#中操作Sqlite数据库,以下是一个封装的操作类(可以打包成dll,本例sqlite.dll):

需要下载并添加引用Sqlite文件System.Data.SQLite.DLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;  // DataTable,DataRow
using System.Data.SQLite;   // System.Data.SQLite.DLL
using System.IO;    // Path

namespace sqlite
{
    /// 
    /// 使用方法:
    /// using System.Data;
    /// using sqlite;
    /// Sqlite ms = new Sqlite("test.sqlite");
    /// string sql = "select * from `posts` where `id`=@id";
    /// Dictionary param = new Dictionary();
    /// param.Add("@id", 1);
    /// DataRow[] rows = ms.getRows(sql, param);
    /// 
    public class Sqlite
    {
        private string _dbpath;

        private SQLiteConnection _conn;
        /// 
        /// SQLite连接
        /// 
        private SQLiteConnection conn
        {
            get
            {
                if (_conn == null)
                {
                    _conn = new SQLiteConnection(
                        string.Format("Data Source={0};Version=3;",
                        this._dbpath
                        ));
                    _conn.Open();
                }
                return _conn;
            }
        }

        /// 
        /// 构造函数
        /// 
        /// sqlite数据库文件路径,相对/绝对路径
        public Sqlite(string dbpath)
        {
            if (Path.IsPathRooted(dbpath))
            {
                this._dbpath = dbpath;
            }
            else
            {
                this._dbpath = string.Format("{0}/{1}", AppDomain.CurrentDomain.SetupInformation.ApplicationBase, dbpath);
            }

        }

        /// 
        /// 获取多行
        /// 
        /// 执行sql
        /// sql参数
        /// 多行结果
        public DataRow[] getRows(string sql, Dictionary param=null)
        {
            List sqlite_param = new List();

            if (param != null)
            {
                foreach (KeyValuePair row in param)
                {
                    sqlite_param.Add(new SQLiteParameter(row.Key, row.Value.ToString()));
                }
            }

            DataTable dt = this.ExecuteDataTable(sql, sqlite_param.ToArray());
            return dt.Select();
        }

        /// 
        /// 获取单行
        /// 
        /// 执行sql
        /// sql参数
        /// 单行数据
        public DataRow getRow(string sql, Dictionary param=null)
        {
            DataRow[] rows = this.getRows(sql, param);
            return rows[0];
        }

        /// 
        /// 获取字段
        /// 
        /// 执行sql
        /// sql参数
        /// 字段数据
        public Object getOne(string sql, Dictionary param=null)
        {
            DataRow row = this.getRow(sql, param);
            return row[0];
        }

        /// 
        /// SQLite增删改
        /// 
        /// 要执行的sql语句
        /// 所需参数
        /// 所受影响的行数
        public int query(string sql, Dictionary param = null)
        {
            List sqlite_param = new List();

            if (param != null)
            {
                foreach (KeyValuePair row in param)
                {
                    sqlite_param.Add(new SQLiteParameter(row.Key, row.Value.ToString()));
                }
            }

            return this.ExecuteNonQuery(sql, sqlite_param.ToArray());
        }

        /// 
        /// SQLite增删改
        /// 
        /// 要执行的sql语句
        /// 所需参数
        /// 所受影响的行数
        private int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)
        {
            int affectedRows = 0;

            System.Data.Common.DbTransaction transaction = conn.BeginTransaction();
            SQLiteCommand command = new SQLiteCommand(conn);
            command.CommandText = sql;
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            affectedRows = command.ExecuteNonQuery();
            transaction.Commit();

            return affectedRows;
        }

        /// 
        /// SQLite查询
        /// 
        /// 要执行的sql语句
        /// 所需参数
        /// 结果DataTable
        private DataTable ExecuteDataTable(string sql, SQLiteParameter[] parameters)
        {
            DataTable data = new DataTable();

            SQLiteCommand command = new SQLiteCommand(sql, conn);
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
            adapter.Fill(data);

            return data;
        }

        /// 
        /// 查询数据库表信息
        /// 
        /// 数据库表信息DataTable
        public DataTable GetSchema()
        {
            DataTable data = new DataTable();

            data = conn.GetSchema("TABLES");

            return data;
        }
    }
}

.net4需要在工程中添加App.config做一下申明:

App.config:



  
    
  
  
    
  
新建一个实例工程(本例wpf),添加引用本例封装成包的sqlite.dll,本例读取了同在App.config中的sqlite文件位置的配置项dbpath

实例代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Configuration; // System.configuration.dll
using sqlite;   //Sqlite.dll
using System.Data;
using note.DataContract;   

namespace note
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // db init
            string dbpath = ConfigurationManager.AppSettings["dbpath"];
            Sqlite ms = new Sqlite(dbpath);

            // get data
            string sql = "select * from `notes` limit 10";
            DataRow[] rows = ms.getRows(sql);

        }
    }
}





你可能感兴趣的:(.NET)