1、在项目工程中,打开NuGet然后搜索Stub.System.Data.SQLite.Core.NetFramework。
2、搜索到后开始安装。安装完成后项目引用中就出现System.data.sqlite,这时候就可以用了。
3、使用下面的代码作为一个数据库帮助类,快速使用是Sqlite数据库。(该方法在wpf和winform均测试过)
public class DataBaseHelp
{
///
/// 链接套接字
///
static SQLiteConnection m_dbConnection { get; set; }
///
/// 生成连接字符串
///
///
private static string CreateConnectionString(string db)
{
SQLiteConnectionStringBuilder connectionString = new SQLiteConnectionStringBuilder();
connectionString.DataSource = @"data/" + db;//此处文件名可以使用变量表示
string conStr = connectionString.ToString();
return conStr;
}
///
/// 连接到数据库
///
///
private static SQLiteConnection dbConnection(string db)
{
m_dbConnection = new SQLiteConnection(CreateConnectionString(db));
m_dbConnection.Open();
return m_dbConnection;
}
///
/// 创建数据库文件,如:text.db
///
/// 文件名
public static void CreateDBFile(string fileName)
{
string path = Environment.CurrentDirectory + @"/Data/";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string databaseFileName = path + fileName;
if (!File.Exists(databaseFileName))
{
SQLiteConnection.CreateFile(databaseFileName);
}
}
///
/// 在指定数据库中创建一个table
/// 如:create table mytab (ID INT PRIMARY KEY NOT NULL, text TEXT NOT NULL);
///
///
///
public static bool CreateTable(string db, string sql)
{
try
{
SQLiteCommand command = new SQLiteCommand(sql, dbConnection(db));
command.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Console.WriteLine("ExecuteNonQuery(" + sql + ")Err:" + ex);
return false;
}
finally
{
closeConn();
}
}
///
/// 返回记录集查询
///
/// sql查询语言
/// 返回查询结果集
public static DataTable SqlTable(string db, string sql)
{
try
{
SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbConnection(db));//sql语句
sqlcmd.CommandTimeout = 120;
SQLiteDataReader reader = sqlcmd.ExecuteReader();
DataTable dt = new DataTable();
if (reader != null)
{
dt.Load(reader, LoadOption.PreserveChanges, null);
}
return dt;
}
catch (Exception ex)
{
Console.WriteLine("SqlReader(" + sql + ")Err:" + ex);
return null;
}
finally
{
closeConn();
}
}
///
/// 执行增删改查操作
///
/// 查询语言
///
public static int ExecuteNonQuery(string db, string sql)
{
try
{
SQLiteCommand cmd;
cmd = new SQLiteCommand(sql, dbConnection(db));
cmd.ExecuteNonQuery().ToString();
return 1;
}
catch (Exception ex)
{
string chejnji="ExecuteNonQuery(" + sql + ")Err:" + ex.Message;
var strDateInfo = "出现应用程序未处理的异常:" + DateTime.Now + "\r\n";
var str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n",
ex.GetType().Name, ex.Message, ex.StackTrace);
WriteLog(str+ chejnji);//日志写入
return 0;
}
finally
{
closeConn();
}
}
static void WriteLog(string str)
{
if (!Directory.Exists("ErrLog"))
{
Directory.CreateDirectory("ErrLog");
}
string CreateTime = DateTime.Now.ToString("yyyy-MM");
using (var sw = new StreamWriter("ErrLog\\" + CreateTime + ".txt", true))
{
sw.WriteLine(str);
sw.WriteLine("---------------------------------------------------------");
sw.Close();
}
}
///
/// 删除数据库
///
/// 文件名
public static void DeleteDBFile(string fileName)
{
string path = Environment.CurrentDirectory + @"/Data/" + fileName;
if (File.Exists(path))
{
File.Delete(path);
}
}
///
/// 在指定数据库中删除一个table
///
/// 表名称
///
public static bool DeleteTable(string db, string tablename)
{
try
{
SQLiteCommand cmd = new SQLiteCommand("DROP TABLE IF EXISTS " + tablename, dbConnection(db));
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Console.WriteLine("ExecuteNonQuery(DROP TABLE IF EXISTS " + tablename + ")Err:" + ex);
return false;
}
finally
{
closeConn();
}
}
///
/// 返回一条记录查询
///
/// sql查询语言
/// 返回字符串数组
public static List<string> SqlRow(string db, string sql)
{
try
{
SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbConnection(db));//sql语句
SQLiteDataReader reader = sqlcmd.ExecuteReader();
if (!reader.Read())
{
return null;
}
List<string> Row = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
Row.Add(reader[i].ToString());
}
reader.Close();
return Row;
}
catch (Exception ex)
{
Console.WriteLine("SqlRow(" + sql + ")Err:" + ex);
return null;
}
finally
{
closeConn();
}
}
///
/// 在指定表中添加列
///
/// 表名
/// 列名
/// 列的数值类型
///
public static bool AddColumn(string db, string tablename, string columnname, string ctype)
{
try
{
SQLiteCommand cmd = new SQLiteCommand("ALTER TABLE " + tablename + " ADD COLUMN " + columnname + " " + ctype, dbConnection(db));
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Console.WriteLine("ExecuteNonQuery(ALTER TABLE " + tablename + " ADD COLUMN " + columnname + " " + ctype + ")Err:" + ex);
return false;
}
finally
{
closeConn();
}
}
///
/// 唯一结果查询
///
/// sql查询语言
/// 返回一个字符串
public static string sqlone(string db, string sql)
{
try
{
SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbConnection(db));//sql语句
return sqlcmd.ExecuteScalar().ToString();
}
catch
{
return "";
}
finally
{
closeConn();
}
}
///
/// 获取一列数据
///
/// 单列查询
/// 返回结果数量
/// 返回一个数组
public static List<string> sqlcolumn(string db, string sql)
{
try
{
List<string> Column = new List<string>();
SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbConnection(db));//sql语句
SQLiteDataReader reader = sqlcmd.ExecuteReader();
while (reader.Read())
{
Column.Add(reader[0].ToString());
}
reader.Close();
return Column;
}
catch (Exception ex)
{
Console.WriteLine("sqlcolumn(" + sql + ")Err:" + ex);
return null;
}
finally
{
closeConn();
}
}
///
/// 关闭数据库连接
///
public static void closeConn()
{
try
{
if (m_dbConnection.State == ConnectionState.Open)
m_dbConnection.Close();
else if (m_dbConnection.State == ConnectionState.Broken)
{
m_dbConnection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("closeConnErr:" + ex);
}
}
}