1.数据库连接(常用连接方法,示例)

1). 添加引用: System.Data.SQLite.DLL 。
2). 打开或创建数据库文件: SQLiteConnection.CreateFile(fileName);
3). 连接数据库: var connection = new SQLiteConnection(connectionString);
connectionString 中包含了数据库的一些配置信息,比如数据库文件路径,数据库密码等,可用 SQLiteConnectionStringBuilder 来创建 connectionString
 string dbPath = Environment.CurrentDirectory + "/test.db";/*指定数据库路径 */
using(SQLiteConnection conn = new SQLiteConnection("Data Source =" + dbPath))
{
conn.Open();
DbCommand comm = conn.CreateCommand();
comm.CommandText = "select * from customer";
comm.CommandType = CommandType.Text;
using (IDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
Response.Write(reader[]);
}
}
}
在web.config或者是app.config中添加如下配置,connectionstring配置节的db就是 SQLite的数据库文件,将它放在Web应用的App_Data目录,|DataDirectory|就代表这个目录的位置,
后面的就是文件名,剩下的就是我们使用企业库访问SQL Server是一样的了。
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null />
</configSections>
<dataConfiguration defaultDatabase=" ">
<providerMappings>
<add databaseType="EntLibContrib.Data.SQLite.SQLiteDatabase, EntLibContrib.Data.SqLite, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null"
name="System.Data.SQLite" />
</providerMappings>
</dataConfiguration>
<connectionStrings>
<add name="sqlite" connectionString="Data Source=|DataDirectory|\db;Pooling=true;FailIfMissing=false"
providerName="System.Data.SQLite" />
</connectionStrings>
</configuration>
 在该工程上引入System.Data.SQLite.DLL(即wrapper),无需引入SQLite3.dll,因为前者已经包装了后者。 
    在代码中import下: "using System.Data.SQLite;" 
 using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite; namespace TestSQLite
{
class MyCSharpSQLite
{
private static string connStr; static void Main(string[] args)
{ connStr = SQLiteConnectionString.GetConnectionString(".\\Data\\EasyDataBase.db");
Console.WriteLine("SQLite Connect String is : {0}", connStr); //连接测试
//testConnect(connStr); //执行查询
ExecQuery("select * from customers"); Console.ReadKey();
} private static void testConnect(string connStr)
{
try
{
SQLiteConnection conn = new SQLiteConnection(connStr); conn.Open();
Console.WriteLine("SQLite Connect OK.");
}
catch (Exception ex)
{
Console.WriteLine("SQLite Connect fail: {0} ", ex.Message);
}
} private static void ExecQuery(string sqlStr)
{
Console.WriteLine(">> Start to query the database....");
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
conn.Open();
SQLiteCommand comm = conn.CreateCommand();
comm.CommandText = sqlStr;
//comm.CommandType = comm.CommandText; using (SQLiteDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[].ToString());
}
}
}
} } /// <summary> /// 生成SQLite连接字符串 /// </summary> public static class SQLiteConnectionString
{ public static string GetConnectionString(string path)
{
return GetConnectionString(path, null);
} public static string GetConnectionString(string path, string password)
{
if (string.IsNullOrEmpty(password))
{
return "Data Source=" + path;
}
else
{
return "Data Source=" + path + ";Password=" + password;
}
} }
}
示例1
 using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite; //需要安装sqlite for vs
namespace MobileTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} public DataSet GetData()
{
try
{
//得到数据库位置
string dbfile = string.Format("{0}\\SqlLiteTest", Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));
//连接字符串
string connStr = string.Format("Data Source={0};Password=123456", dbfile);
SQLiteConnection conn = new SQLiteConnection(connStr);
string sql = "SELECT Id,Name,age FROM tbl_liteTest";
SQLiteDataAdapter slda = new SQLiteDataAdapter(sql, conn);
DataSet ds = new DataSet();
slda.Fill(ds);
return ds;
}
catch (Exception)
{ throw;
}
}
private void Form1_Load(object sender, EventArgs e)
{
DataSet ds = GetData();
foreach (DataRow item in ds.Tables[].Rows)
{
this.comboBox1.Items.Add(item["Name"].ToString());
}
}
}
}

示例2

 SQLiteConnection cnn = new SQLiteConnection();
cnn.ConnectionString = @"Data Source=c:sqlite-3_5_0mytest.db";
cnn.Open(); SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = cnn;
cmd.CommandText = "SELECT * FROM mytable1";
SQLiteDataAdapter da = new SQLiteDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);

示例3

下载ADO.NET2.0 Provider for SQLite。下载binaries zip版就可以了。下载完后解压缩,可以在bin目录下找到System.Data.SQLite.DLL。在vs2008中用Add Reference功能把System.Data.SQLite.DLL加到工程里就可以了。

 string datasource = "d:/sqllite/sqlite.net/bin/test.db3";
system.data.sqlite.sqliteconnection.createfile(datasource);
//连接数据库
system.data.sqlite.sqliteconnection conn = new system.data.sqlite.sqliteconnection();
system.data.sqlite.sqliteconnectionstringbuilder connstr = new system.data.sqlite.sqliteconnectionstringbuilder();
connstr.datasource = datasource;
connstr.password = "admin";//设置密码,sqlite ado.net实现了数据库密码保护
conn.connectionstring = connstr.tostring();
conn.open();
//创建表
system.data.sqlite.sqlitecommand cmd = new system.data.sqlite.sqlitecommand();
string sql = "create table test(username varchar(20),password varchar(20))";
cmd.commandtext = sql;
cmd.connection = conn;
cmd.executenonquery();
//插入数据
sql = "insert into test values('a','b')";
cmd.commandtext = sql;
cmd.executenonquery();
//取出数据
sql = "select * from test";
cmd.commandtext = sql;
system.data.sqlite.sqlitedatareader reader = cmd.executereader();
stringbuilder sb = new stringbuilder();
while (reader.read())
{
sb.append("username:").append(reader.getstring()).append("\n")
.append("password:").append(reader.getstring());
}
console.writeline(sb.tostring());
console.read();

2.C#对SQLLite的DML操作示例

/*这里新建了一个HyData目录存放数据库*/
string connStr = @"Data Source=" + System.Environment.CurrentDirectory + @"\HyData\HyData.db3;Initial Catalog=sqlite;Integrated Security=True;Max Pool Size=10"; /*执行Sql语句
创建一个表: ExecuteSql("create table HyTest(TestID TEXT)");
插入些数据: ExecuteSql("insert into HyTest(TestID) values('1001')");
*/
private void ExecuteSql(string sqlStr)
{
using (DbConnection conn = new SQLiteConnection(connStr))
{
conn.Open();
DbCommand comm = conn.CreateCommand();
comm.CommandText = sqlStr;
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
} /*执行查询
ExecQuery("select * from HyTest");
*/
private void ExecQuery(string sqlStr)
{
using (DbConnection conn = new SQLiteConnection(connStr))
{
conn.Open();
DbCommand comm = conn.CreateCommand();
comm.CommandText = sqlStr;
comm.CommandType = CommandType.Text; using (IDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
MessageBox.Show(reader[].ToString());
}
}
}
} /* 执行查询返回DataSet */ private DataSet ExecDataSet(string sqlStr)
{
using (SQLiteConnection conn = new SQLiteConnection(connStr))
{
conn.Open();
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlStr;
cmd.CommandType = CommandType.Text; SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds); return ds;
}
}
System.Data.SQLite.SQLiteConnection conn =new System.Data.SQLite.SQLiteConnection(@"Data Source=d:\maindb.db;Version=3");

string datasource = "d:\\maindb.db";
//连接数据库
System.Data.SQLite.SQLiteConnection conn =new System.Data.SQLite.SQLiteConnection();
System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder();
connstr.DataSource = datasource;
conn.ConnectionString = connstr.ToString();
conn.Open();
System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand();
//取出数据
string sql = "SELECT * FROM Source";
cmd.CommandText = sql;
System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.Append("ID:").Append(reader.GetString()).Append("\n")
.Append("NAME:").Append(reader.GetString()); }
MessageBox.Show(sb.ToString());

3.对SQLLite DML操作类封装

使用C#对SQLLite进行操作的更多相关文章

  1. (转)SQLLite数据操作

    原文:http://dreamboy.blog.51cto.com/3180937/722352 SQLLite数据操作 一般数据采用的固定的静态数据类型,而SQLite采用的是动态数据类型,会根据存 ...

  2. 09_Android中ContentProvider和Sqllite混合操作,一个项目调用另外一个项目的ContentProvider

    1.  编写ContentPrivider提供者的Android应用 清单文件 <?xml version="1.0" encoding="utf-8"? ...

  3. Android:SQLiteOpenHelper类(SQLlite数据库操作)详细解析

    前言 SQLite数据库操作在Android开发中非常常用 今天我将带大家全面了解关于SQLite数据库的操作(增.删.查.改) 目录 1. SQLite数据库介绍 SQLite是Android内置的 ...

  4. flutter插件汇总

    audio_recorder: any #录音.播放 flutter_sound: ^#录音 dropdown_menu: ^#下拉菜单 simple_permissions:#权限获取 easy_a ...

  5. flutter 常用插件

    audio_recorder: any #录音.播放 flutter_sound: ^1.1.5#录音 dropdown_menu: ^1.1.0#下拉菜单 simple_permissions:#权 ...

  6. 奔跑吧DKY——团队Scrum冲刺阶段-Day 7

    今日完成任务 谭鑫:将人物图添加到游戏以及商店界面中,实现商店的选择换装功能 黄宇塘:制作人物图.背景图 赵晓海:阅读所有代码测试所有功能,美化部分界面 方艺雯:为商店界面及关于界面添加必要文字说明 ...

  7. python笔记-19 javascript补充、web框架、django基础

    一.JavaScript的补充 1 正则表达式 1.1 test的使用 test 测试是否符合条件 返回true or false 1.2 exec的使用 exec 从字符串中截取匹配的字符 1.3 ...

  8. 一个驱动导致的内存泄漏问题的分析过程(meminfo->pmap->slabtop->alloc_calls)

    关键词:sqllite.meminfo.slabinfo.alloc_calls.nand.SUnreclaim等等. 下面记录一个由于驱动导致的内存泄漏问题分析过程. 首先介绍问题背景,在一款嵌入式 ...

  9. Flutter-常用插件庫

    alibaba/flutter_boost:路由 install_plugin 2.0.0#app下载更新插件 audio_recorder: any #录音.播放 flutter_sound: ^1 ...

随机推荐

  1. JQuery在循环中绑定事件的问题详解

    JQuery在循环中绑定事件的问题详解 有个页面上需要N个DOM,每个DOM里面的元素ID都要以数字结尾,比如说 ? 1 2 3 <input type="text" nam ...

  2. 介绍开源的.net通信框架NetworkComms框架之九 合并DLL

    原文网址: http://www.cnblogs.com/csdev Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是 ...

  3. 使用ASP.NET 上传文件 三种类型判断方法(后缀,MIME,数据流)

    #region 一. 安全性比较低,把文本文件1.txt改成1.jpg照样可以上传,但其实现方法容易理解,实现也简单,所以网上很多还是采取这种方法. Boolean fileOk = false; s ...

  4. MVC、ORM、CURD、ActiveRecord、单一入口的概念

    MVC MVC是一个设计模式,它强制性的使应用程序的输入.处理和输出分开.使用MVC应用程序被分成三个核心部件:模型(M).视图(V).控制器(C),它们各自处理自己的任务. 视图 :视图是用户看到并 ...

  5. bzoj 3131: [Sdoi2013]淘金

    #include<cstdio> #include<iostream> #include<queue> #include<algorithm> #def ...

  6. Mike的农场 (BZOJ 4177)

    题目大意: 给N个东西分AB类,分到A类和B类分别得到相应的钱记为A[i],B[i],然后有一些冲突关系<x,y,z>,如果物品x,y不同类需要付出z的钱.还有一些外快<S,x,y& ...

  7. Android控件— — —ImageView

    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android=" ...

  8. CSS中相对定位与绝对定位

    看了几个讲解定位的博客,觉得还不错,分享之: 博客一:http://blog.sina.com.cn/s/blog_4bcf4a5e010008o0.html 文章中,主要需要参考的有两点: 1,相对 ...

  9. WCF vs ASMX WebService

    This question comes up a lot in conversations I have with developers. “Why would I want to switch to ...

  10. Turing Tree_线段树&树状数组

    Problem Description After inventing Turing Tree, 3xian always felt boring when solving problems abou ...