一、简介
SQLite是一个进程内的轻量级嵌入式数据库,它的数据库就是一个文件。下面是我用 C# 语言对 SQLite 的操作DEMO。
二、创建数据库
1.sqlite数据库用DB Browser for SQLlite打开,创表库sqlitdb.db
2.给表里加一点数据发下:
二、编写C#代码
1.#中安装System.Data.SQLite 组件
2.创建一个SQliteUtil.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sqlite.Module;
namespace Sqlite.Util
{
class SQliteUtil
{
public static void dbinsert()
{
string dbfile = @"URI=file:H:\netspace\sqlite\sqlitedb.db";
SQLiteConnection conn = new SQLiteConnection(dbfile);
conn.Open();
string sql = "INSERT into test( name, context) VALUES( 1, '备注"+new Random().Next()+"');";
SQLiteCommand cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
public static List<Test> dbselect()
{
string dbfile = @"URI=file:H:\netspace\sqlite\sqlitedb.db";
SQLiteConnection conn = new SQLiteConnection(dbfile);
conn.Open();
string sql = "select * from test;";
SQLiteDataAdapter da = new SQLiteDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
da.Dispose();
conn.Close();
List<Test> list = new List<Test>();
foreach(DataRow row in dt.Rows)
{
string id = row["id"].ToString();
string name = row["name"].ToString();
string context = row["context"].ToString();
Test test = new Test();
test.id = id;
test.name = name;
test.context = context;
list.Add(test);
}
return list;
}
}
}
3.调用SQLiteUtil
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sqlite.Util;
using execl_word;
using Sqlite.Module;
namespace Sqlite
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
SQliteUtil.dbinsert();
}
private void button2_Click(object sender, EventArgs e)
{
List<Test> list = SQliteUtil.dbselect();
string str = JsonNewtonsoft.ToJSON(list);
textBox1.Text = str;
}
}
}
源码:点击下载