引入SQLlite.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sqllite
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//创建数据库
bool CreatDb() {
string dbPath = "./test.db";
try
{
SQLiteConnection.CreateFile(dbPath);
return true;
}
catch (Exception ex)
{
throw new Exception("新建数据库文件" + dbPath + "失败:" + ex.Message);
}
}
//创建新表
static public void NewTable(string dbPath, string tableName)
{
SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);
if (sqliteConn.State != System.Data.ConnectionState.Open)
{
sqliteConn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = sqliteConn;
cmd.CommandText = "CREATE TABLE " + tableName + "(Name varchar,Team varchar)";
cmd.ExecuteNonQuery();
}
sqliteConn.Close();
}
//插入数据
void insert(String sql,String dbPath) {
SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);
if (sqliteConn.State != ConnectionState.Open)
{
sqliteConn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = sqliteConn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
sqliteConn.Close();
}//查询全部
static void Select(String sql, String dbPath) {
SQLiteConnection sqliteConn = new SQLiteConnection("data source=" + dbPath);
SQLiteCommand command = new SQLiteCommand();
if (sqliteConn.State != ConnectionState.Open)
{
sqliteConn.Open();
command.Connection = sqliteConn;
command.CommandText = sql;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
MessageBox.Show("Name: " + reader["Name"] + "\tScore: " + reader["Team"]);
}
sqliteConn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
CreatDb();
NewTable("test.db", "tablea");
insert("insert into tablea (Name, Team) values ('Myself', 'blue')","test.db");
}
private void button2_Click(object sender, EventArgs e)
{
Select("select * from tablea", "test.db");
}
}
}