原文发布时间为:2011-12-10 —— 来源于本人的百度文章 [由搬家工具导入]

http://www.csharpcity.com/sqlite-ado-net-c-4-0/

Getting SQLite to run (the ADO.NET version) under C# 4.0 is a bit tricky. You can follow the steps below to get it to work.

First, download SQLite (the ADO.NET version) from here. This is the sourceforge page for the official project. Install it.

Second, download SQLiteAdmin, a free, awesome GUI tool for SQLite. You can get it here.

Next, create a database using SQLiteAdmin. Add a single table with a single row, so that you can test that things work.

Then, launch up Visual Studio 2010 and create a new project. Add a reference to the System.Data.SQLite.dll file (located in SQLite.NETbin). I recommend copying the DLL into an “extlib” folder in your project and referencing that.

Finally, run a query and see how things go! Here’s a quick method I hacked together:

        public static DataTable ExecuteQuery(string sql)        {            // Validate SQL            if (string.IsNullOrWhiteSpace(sql))            {                return null;            }            else            {                if (!sql.EndsWith(";"))                {                    sql += ";";                }                SQLiteConnection connection = new SQLiteConnection("Data Source=blah.db");                connection.Open();                SQLiteCommand cmd = new SQLiteCommand(connection);                cmd.CommandText = sql;                DataTable dt = new DataTable();                SQLiteDataReader reader = cmd.ExecuteReader();                dt.Load(reader);                reader.Close();                connection.Close();                return dt;            }        }

The only wierd thing is that the function returns a DataTable, which essentially makes it easy for you to iterate.

Then, call this function, and trace out the results:

DataTable table = ExecuteQuery("SELECT * FROM someTable");foreach (DataRow row in table.Rows) {  Debug.Trace("Record: id=" + row["id"] + " name=" + row["name"]);}

But wait! You get this annoying and un-googlable error:

Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

Ouch! It seems like you’re running a .NET 2.0 library, which is ok, but it has unmanaged code in it, which may or may not be ok; we need to tell our project explicitly that we can run it.

Right-click on your project, and add a new file; select “Application Config File” (depicted below):

Paste the following XML inside the configuration tag:

<startup useLegacyV2RuntimeActivationPolicy="true">    <supportedRuntime version="v4.0"/>  </startup>

And viola! The exception should disappear. You should see something like (assuming you inserted two names):

Record: id=1 Name=CSharpCityRecord: id=2 Name=Google

That wasn’t so hard, now was it?

 

===

using System.Configuration;
using System.Data;
using System.Data.SQLite;

namespace SQLliteTest
{
    public class SqliteHelper
    {
        /// <summary>
        /// 获得连接对象
        /// </summary>
        /// <returns></returns>
        public static SQLiteConnection GetSQLiteConnection()
        {
            return
                new SQLiteConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString);
        }
        private static void PrepareCommand(SQLiteCommand cmd, SQLiteConnection conn, string cmdText, params SQLiteParameter[] commandParameters)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Parameters.Clear();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandType = CommandType.Text;
            cmd.CommandTimeout = 30;
            if (commandParameters != null)
            {
                cmd.Parameters.AddRange(commandParameters);
            }
        }

        public static DataSet ExecuteDataset(string cmdText, params SQLiteParameter[] commandParameters)
        {
            var ds = new DataSet();
            var command = new SQLiteCommand();
            using (SQLiteConnection connection = GetSQLiteConnection())
            {
                PrepareCommand(command, connection, cmdText, commandParameters);
                var da = new SQLiteDataAdapter(command);
                da.Fill(ds);
            }
            return ds;
        }

        public static DataRow ExecuteDataRow(string cmdText, params SQLiteParameter[] commandParameters)
        {
            DataSet ds = ExecuteDataset(cmdText, commandParameters);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                return ds.Tables[0].Rows[0];
            return null;
        }

        /// <summary>
        /// 返回受影响的行数
        /// </summary>
        /// <param name="cmdText">a</param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static int ExecuteNonQuery(string cmdText, params SQLiteParameter[] commandParameters)
        {
            var command = new SQLiteCommand();
            using (SQLiteConnection connection = GetSQLiteConnection())
            {
                PrepareCommand(command, connection, cmdText, commandParameters);

                return command.ExecuteNonQuery();
            }
        }
        /// <summary>
        /// 返回SqlDataReader对象
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters">传入的参数</param>
        /// <returns></returns>
        public static SQLiteDataReader ExecuteReader(string cmdText, params SQLiteParameter[] commandParameters)
        {
            var command = new SQLiteCommand();
            SQLiteConnection connection = GetSQLiteConnection();
            try
            {
                PrepareCommand(command, connection, cmdText, commandParameters);
                SQLiteDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                return reader;
            }
            catch
            {
                connection.Close();
                throw;
            }
        }

        /// <summary>
        /// 返回结果集中的第一行第一列,忽略其他行或列
        /// </summary>
        /// <param name="cmdText"></param>
        /// <param name="commandParameters">传入的参数</param>
        /// <returns></returns>
        public static object ExecuteScalar(string cmdText, params SQLiteParameter[] commandParameters)
        {
            var cmd = new SQLiteCommand();
            using (SQLiteConnection connection = GetSQLiteConnection())
            {
                PrepareCommand(cmd, connection, cmdText, commandParameters);
                return cmd.ExecuteScalar();
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="recordCount"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="cmdText"></param>
        /// <param name="countText"></param>
        /// <param name="commandParameters"></param>
        /// <returns></returns>
        public static DataSet ExecutePager(ref int recordCount, int pageIndex, int pageSize, string cmdText,
                                           string countText, params SQLiteParameter[] commandParameters)
        {
            if (recordCount < 0)
                recordCount = int.Parse(ExecuteScalar(countText, commandParameters).ToString());
            var ds = new DataSet();
            var command = new SQLiteCommand();
            using (SQLiteConnection connection = GetSQLiteConnection())
            {
                PrepareCommand(command, connection, cmdText, commandParameters);
                var da = new SQLiteDataAdapter(command);
                da.Fill(ds, (pageIndex - 1) * pageSize, pageSize, "result");
            }
            return ds;
        }
    }
}

.NET 4.0中使用sqlite的更多相关文章

  1. Visual Studio 2010(.NET 4.0)中使用SQLite.NET

    Visual Studio 2010(.NET 4.0)中使用SQLite.NET   2011年4月1日 | 分类: DataBase, DOTNET | 标签: .net 4.0, SQLite. ...

  2. Android中的SQLite使用学习

    Android中的SQLite使用学习 SQLite是非常流行的嵌入式关系型数据库,轻载, 速度快,而且是开源.在Android中,runtime提供SQLite,所以我们可以使用SQLite,而且是 ...

  3. C#中使用SQLite数据库简介(上)

    [SQLite数据库] SQLite是一个开源的轻量级的桌面型数据库,它将几乎所有数据库要素(包括定义.表.索引和数据本身)都保存在一个单一的文件中.SQLite用C编写实现,它在内存消耗.文件体积. ...

  4. 在项目中使用SQLite数据库小结

    ------------------------------------------------------------------------推荐: - VS2012 使用 1.0.84 版的库 - ...

  5. Android中使用sqlite笔记

    1.实现SQLiteHelper来在android中使用SQLite.代码如下,来自android官网. public class FeedReaderDbHelper extends SQLiteO ...

  6. Android 开发中使用 SQLite 数据库

    SQLite 介绍 SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能. 此外它还是开源的,任何人都可以使用它.许多开源项目((Mozilla, PHP ...

  7. android中与SQLite数据库相关的类

    为什么要在应用程序中使用数据库?数据库最主要的用途就是作为数据的存储容器,另外,由于可以很方便的将应用程序中的数据结构(比如C语言中的结构体)转化成数据库的表,这样我们就可以通过操作数据库来替代写一堆 ...

  8. 在Windows Phone 8.1中使用Sqlite数据库

    前言 我的工作目前不涉及到Windows phone的开发,但是业余时间也开发过几款app.以前由于各种条件的限制,只接触到WP8.0设备的app开发. 最近几个月开始将WP8的应用迁移到WP8.1, ...

  9. 在Java中使用SQLite的教程(转)

    简介:这是在Java中使用SQLite的教程的详细页面,介绍了和java,有关的知识.技巧.经验,和一些java源码等. 简单的在Java中使用SQLite的教程 使用SQLiteJDBC封装 www ...

随机推荐

  1. jpeglib的使用

    1. 解压jpeglib tar xvzf libjpeg-turbo-1.2.1.tar.gz 2. 阅读里面的说明文件,得到jpeg解压缩的一般步骤: /*Allocate and initial ...

  2. Python全栈day 01

    Python全栈day 01 一.计算机认识 用户 软件,类似微信.QQ.游戏等应用程序,由程序员编写,在系统中运行,完成各种活动,方便人们使用. 操作系统,主要分为windows系统.Linux系统 ...

  3. 各种Nand的总结

    1. 微观 NAND闪存NAND是非易失性存储技术,NAND闪存由多个存放以位(bit)为单位的单元构成,这些位通过电荷被打开或关闭,如何组织这些开关单元来储存在SSD上的数据,也决定了NAND闪存的 ...

  4. C++ 基础 初始化列表

    当一个类组合了其他类,或者使用了 const 成员,就要用 初始化列表. Class A {...}; Class B {...}; Class C { private: A a; B b; int ...

  5. Android面试收集录3 ContentProvider详解

    1.ContentProvider简单介绍 1.1.定义 ContentProvider,即内容提供者属于Android的四大组件之一. 1.2.作用 进程间进行数据交互&共享,即跨进程通信. ...

  6. BZOJ 5004: 开锁魔法II

    比较显然 #include<cstdio> #include<algorithm> #include<cstring> using namespace std; i ...

  7. adnroid 打包问题 :compileReleaseJavaWithJavac

    今天打包的时候,由于着急.改了些本地的变化就assembleRelease. 然后就报错: compileReleaseJavaWithJavac 后来网上乱找,.... 之后我想到先跑一下,果然是因 ...

  8. 我给女朋友讲编程CSS系列(4) CSS盒子模型

    什么是CSS盒子模型?如何学习CSS的盒子模型? 这篇文章,以 [分享 + 结论]  的方式来写. 1,  看w3school的[CSS 框模型概述] 网址为: http://www.w3school ...

  9. 嗯,ACM按照这个一步一步来。

        转一个搞ACM需要的掌握的算法.   要注意,ACM的竞赛性强,因此自己应该和自己的实际应用联系起来. 适合自己的才是好的,有的人不适合搞算法,喜欢系统架构,因此不要看到别人什么就眼红, 发挥 ...

  10. Python 快速部署安装所需模块

    需求 我们需要在拷给别人或者提交至服务器也用同样的模块,好保持和开发的一样,所以我们需要自己手动写配置模块信息. 方法 在根目录下创建一个 requirements.txt  文件 里面写 模块名== ...