惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
Attack and Defense Labs
Attack and Defense Labs
V2EX - 技术
V2EX - 技术
O
OpenAI News
S
Secure Thoughts
H
Heimdal Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Schneier on Security
Schneier on Security
H
Hacker News: Front Page
S
Security Affairs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
The Register - Security
The Register - Security
GbyAI
GbyAI
Cloudbric
Cloudbric
MongoDB | Blog
MongoDB | Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
K
Kaspersky official blog
Forbes - Security
Forbes - Security
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Scott Helme
Scott Helme
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Cloudflare Blog
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
Webroot Blog
Webroot Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog
T
Tor Project blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
N
News and Events Feed by Topic
阮一峰的网络日志
阮一峰的网络日志
I
Intezer
V
V2EX
T
Tailwind CSS Blog
SecWiki News
SecWiki News
NISL@THU
NISL@THU
C
Check Point Blog

博客园 - 说不得

折腾了两天的跨站脚本提交问题,与IIS7有关 MongoDB 服务启动时指定dbpath DataGridView绑定行号 【转帖】三种决不能放进数据库的东西 Func<T, TResult>的一个使用场合 没别的,来张截图好了 SqlBulkCopy使用心得 使用两个信号量实现主线程和线程池同步 VS2010 出现错误提示“Error Creating Control - Object reference not set to an instance of an objec” 的解决方法 Win7 下使用 SQLite Expert 操作C盘下的数据库发生错误:Attempt to write a readonly database. C#查找某一窗口并按钮 再见,Google 使用ManagedSpyLib监视.net程序中控件属性的变化 计算两张黑白图片的相似度 使用c#把一个32位整数按位相加最快的方法是什么? 关于变量在循环内声明还是在循环外声明 轻量级分页控件 安装sqlserver2008时出现“Rule "Previous releases of Microsoft Visual Studio 2008" failed.”错误的解决办法 最近见过的垃圾代码 - 说不得 - 博客园
SQLite.Net操作类
说不得 · 2010-06-28 · via 博客园 - 说不得

为了便于使用SQLite.Net,参照微软企业库中数据组件的写法写了这个类,无非就是为了便于使用。

下面是代码:

代码

using System;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;namespace IdentifyCode.Data
{
    
public class Database
    {
        
/// <summary>
        
///   构造函数
        
/// </summary>
        
/// <param name="dataSource">数据文件</param>
        public Database(string dataSource)
            : 
this(dataSource, falsetrue)
        {
        }
/// <summary>
        
/// 构造函数
        
/// </summary>
        
/// <param name="dataSource">数据文件</param>
        
/// <param name="readOnly">是否只读</param>
        
/// <param name="pooling">是否使用连接池</param>
        public Database(string dataSource, bool readOnly, bool pooling)
        {
            
if (!File.Exists(dataSource))
            {
                SQLiteConnection.CreateFile(dataSource);
            }
            SQLiteConnectionStringBuilder sb 
= new SQLiteConnectionStringBuilder
            {
                DataSource 
= dataSource,
                Version 
= 3,
                ReadOnly 
= readOnly,
                Pooling 
= pooling
            };
            ConnectionString 
= sb.ToString();
        }
/// <summary>
        
///   连接字符串
        
/// </summary>
        public static string ConnectionString { getprivate set; }/// <summary>
        
///   获取Sql语句命令
        
/// </summary>
        
/// <param name = "query"></param>
        
/// <returns></returns>
        public DbCommand GetSqlStringCommand(string query)
        {
            
if (String.IsNullOrEmpty(query))
            {
                
throw new ArgumentException("查询字符串不能为空。");
            }

            DbCommand command 

= new SQLiteCommand(query) { CommandType = CommandType.Text };
            
return command;
        }
public DbCommand GetSqlStringCommand(string query, DbTransaction transaction)
        {
            DbCommand command 
= GetSqlStringCommand(query);
            command.Transaction 
= transaction;
            
return command;
        }
public SQLiteTransaction GetTransaction()
        {
            SQLiteConnection conn 
= new SQLiteConnection(ConnectionString);
            
if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            
return conn.BeginTransaction();
        }
/// <summary>
        
///   添加参数
        
/// </summary>
        
/// <param name = "command"></param>
        
/// <param name = "dbType"></param>
        public void AddInParameter(DbCommand command, DbType dbType)
        {
            command.Parameters.Add(
new SQLiteParameter(dbType));
        }
/// <summary>
        
///   添加参数
        
/// </summary>
        
/// <param name = "command"></param>
        
/// <param name = "dbType"></param>
        
/// <param name = "value"></param>
        public void AddInParameter(DbCommand command, DbType dbType, object value)
        {
            
if (value == null)
            {
                value 
= "null";
            }
            command.Parameters.Add(
new SQLiteParameter(dbType) { Value = value });
        }
/// <summary>
        
///   执行
        
/// </summary>
        
/// <param name = "command"></param>
        
/// <returns></returns>
        public long ExecuteNonQuery(DbCommand command)
        {
            
//如果包含事务,就执行返回,不管连接
            if (command.Transaction != null)
            {
                
return command.ExecuteNonQuery();
            }
using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                
if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                command.Connection 
= conn;
                
return command.ExecuteNonQuery();
            }
        }
/// <summary>
        
///   执行
        
/// </summary>
        
/// <param name = "command"></param>
        
/// <returns></returns>
        public DbDataReader ExecuteReader(DbCommand command)
        {
            SQLiteConnection conn 
= new SQLiteConnection(ConnectionString);
            
try
            {
                
if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                command.Connection 
= conn;
                
return command.ExecuteReader();
            }
            
catch
            {
                
if (conn.State != ConnectionState.Closed)
                {
                    conn.Close();
                }
                
throw;
            }
        }
public long ExecuteScalar(DbCommand command)
        {
            
using (SQLiteConnection conn = new SQLiteConnection(ConnectionString))
            {
                
if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                command.Connection 
= conn;
                
object obj = command.ExecuteScalar();
                
long l = (long)obj;
                
return l;
            }
        }
    }
}

使用方法

1.带事务:

代码

Database db = new Database(dataSource);
using (SQLiteTransaction tran = db.GetTransaction())
{
    
using (DbCommand command = db.GetSqlStringCommand(sqlString, tran))
    {
        
foreach (Entity entity in list)
        {
            db.AddInParameter(command, DbType.String, ...);
            ...

            db.ExecuteNonQuery(command);
            command.Parameters.Clear();
        }

        tran.Commit();
    }
}

2.不带事务:

代码

Database db = new Database(dataSource);
using (DbCommand command = db.GetSqlStringCommand(sqlString))
{
    
foreach (Entity entity in list)
    {
        db.AddInParameter(command, DbType.String, ...);
        ...

        db.ExecuteNonQuery(command);
        command.Parameters.Clear();
    }
}

因为SQLite默认对每个操作打开一个事务,所以如果不声明事务的话,对于任何影响超过1行数据的操作都将会消耗非常长的时间。