使用的命名空间为 using System.Data.SQLite;
使用vs时,在“工具”->”NuGet包管理器“下可以搜索下载此工具包;
构建数据库文件
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite;
namespace WinFormsApp1.Func.DB
{
class Class1
{
public void test()
{
//构建数据库文件
SQLiteConnection.CreateFile("数据库文件路径");
//用sqliteconnection对象 连接数据库
string sqlConnnection_command = "Data Source=" +"数据库路径"+";"+"Version=3;";
SQLiteConnection connection = new SQLiteConnection(sqlConnnection_command);
//向数据库文件中写入”“表”
{
//sql命令
string sql_creatTable = "CREATE TABLE if not exists "
+" 表名 "
+"(列名1 列属性1,列名2 列属性2)";
//使用sqliteCommand对象执行sql命令;(可以在构造时直接写入Connecetion和CommandText属性)
SQLiteCommand command = new SQLiteCommand();
{
connection.Open();
command.Connection = connection;
command.CommandText = sql_creatTable;
command.ExecuteNonQuery();
connection.Close();
}
}
//向数据库中插入数据
{
//备注:列*的值如果是字符串,要加单引号;
string sql_insert = "insert into "+"表名"
+"(" + "列名1,列名2"+")"
+" values "
+"(" + "列1的值,列2的值"+");";
connection.Open();
SQLiteCommand command = new SQLiteCommand(sql_insert, connection);
command.ExecuteNonQuery();
connection.Close();
}
//查询数据库
{
string sql_select = "select * from "+ "表名"
+"order by 列名 desc";
connection.Open();
SQLiteCommand command = new SQLiteCommand(sql_select, connection);
SQLiteDataReader reader = command.ExecuteReader();
while (!reader.Read()) {
Console.WriteLine(reader["列名*"]);
}
connection.Close();
}
}
}
}