VS使用SQLite数据库(主要参考增删改查的代码与新建数据库文件)
参考链接:https://my.oschina.net/u/4518054/blog/4755744?hmsr=kaifa_aladdin
引用——》添加——》管理NuGet程序包——》System.Data.SQLite
SQLite的安装及使用(主要参考新建数据库文件)
参考链接:https://blog.csdn.net/weixin_41656968/article/details/80338626
下载地址:https://www.sqlite.org/download.html
只是创建SQLite数据库下载sqlite-tools-win32-x86-3370200.zip即可
增删改查封装类:https://www.cnblogs.com/123fang/articles/11433033.html
封装类实例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.Common;
using System.Data.SQLite;
namespace SQLiteTest
{
class sqliteHelper
{
static readonly string DB_PATH = "Data Source=D:/software Installation/sqlite-tools-win32-x86-3370200/test.db";
/// <summary>
/// 查询数据
/// </summary>
/// <param name="SQL"></param>
/// <param name="db"></param>
/// <returns></returns>
public static DataTable SelectDB(string SQL, string db = "MydataBase")
{
DataTable dt = new DataTable();
try
{
Console.WriteLine("查询数据,SQL:" + SQL);
string dbFile = System.AppDomain.CurrentDomain.BaseDirectory + db + @".db";
string connString = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dbFile);//拼全连接字符串
SQLiteConnection conn = new SQLiteConnection(DB_PATH);//当前连接字符串写死了
SQLiteDataAdapter adapter = new SQLiteDataAdapter(SQL, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
//关闭连接,释放资源
conn.Close();
conn.Dispose();
adapter.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("查询异常:" + ex.ToString());
return dt;
}
return dt;
}
#region 增删改数据
/// <summary>
/// 增删改数据
/// </summary>
/// <param name="SQL"></param>
/// <param name="db">操作的数据库名称</param>
/// <returns></returns>
public static bool OperationDB(string SQL, string db = "MydataBase")
{
try
{
Console.WriteLine("增删改数据,SQL:" + SQL);
string dbFile = System.AppDomain.CurrentDomain.BaseDirectory + db + @".db";
string connString = string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dbFile);
SQLiteConnection conn = new SQLiteConnection(DB_PATH);
conn.Open();
string Sql = string.Format(SQL);
SQLiteCommand insertData = new SQLiteCommand(Sql, conn);
insertData.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine("增删改数据,异常:" + ex.ToString());
return false;
}
return true;
}
#endregion
}
}
封装类的使用:
string sql = " SELECT * FROM Test_User ";
DataTable dt = sqliteHelper.SelectDB(sql);
for(int i = 0 ; i < dt.Rows.Count ; i++)
{
Console.WriteLine("name=" + dt.Rows[i]["name"].ToString() + " age=" + dt.Rows[i]["age"].ToString());
}
string insertSql = "INSERT INTO Test_User values('444','444')";
var dt2= sqliteHelper.OperationDB(insertSql);
Console.WriteLine( "dt2=" + dt2);