2022-11-19 乐帮网
c# sqlite
C#在NetFramwork4.0中使用Sqlite,如果需要同时兼容Linux和Windows平台,那么我们需要使用 Mono跨平台,如果你使用的是.Net5或.Net6那么就不需要这篇文章。
NetFramwork4.0 Sqllite, 跨平台 兼容Mono模式。
其实在mono的官网早就有公布在linux下的sqlite解决方案,可心参考:https://www.mono-project.com/docs/database-access/providers/sqlite/
首先新建一个控制台程序(.netframwork4.0) ,然后在Nuget中搜索引入:Mono.Data.Sqlite ,为了编写简单的SQL语句在Nuget中我又使用了Dapper,所以还需要在Nuget上安装Dapper。
编写示例代码如下:
public class DbProvider
{
private const string _initSql = @" CREATE TABLE IF NOT EXISTS configure (id INTEGER PRIMARY KEY AUTOINCREMENT,code TEXT NOT NULL UNIQUE,name TEXT NOT NULL,status INTEGER NOT NULL DEFAULT (0),val TEXT NOT NULL,updatedate DATETIME DEFAULT (datetime('now', 'localtime') ) ,updater TEXT DEFAULT(''),remark TEXT DEFAULT('')); ";
private const string _sqlData = @" Insert into configure (code,name,val,remark)
Select 'NET_GPSPORT_1','GPS串口号','2','通讯配置'
union
Select 'NET_GPSPORT_2','GPS串口号','12','通讯配置'
union
Select 'NET_OBDPORT','OBD串口号','4','通讯配置';";
private string _connectionStr;
public DbProvider()
{
string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "vkt.db");
_connectionStr = string.Format("URI=file:{0};version=3;", path);
try
{
if (!File.Exists(path))
{
using (SqliteConnection conn = new SqliteConnection(_connectionStr))
{
conn.Open();
using (var command = conn.CreateCommand())
{
command.CommandText = _initSql + _sqlData;
command.ExecuteNonQuery();
command.Dispose();
}
conn.Close();
}
}
}
catch (Exception ex)
{
//_logger.Error(ex);
}
}
public ConfigDbModel GetConfig(string code)
{
try
{
using (SqliteConnection conn = new SqliteConnection(_connectionStr))
{
conn.Open();
string sql = @"Select id,code,name,status,val,updatedate,updater,remark from configure where status>-1 and code=@code";
var result = conn.Query<ConfigDbModel>(sql, new { code = code }).FirstOrDefault();
conn.Close();
return result;
}
}
catch (Exception ex)
{
//_logger.Error(ex);
}
return null;
}
public List<ConfigDbModel> GetConfigs()
{
var list = new List<ConfigDbModel>();
string sql = @"Select id,code,name,status,val,updatedate,updater,remark from configure ";
try
{
using (SqliteConnection conn = new SqliteConnection(_connectionStr))
{
conn.Open();
var result = conn.Query<ConfigDbModel>(sql).ToList();
conn.Close();
return result;
}
}
catch (Exception ex)
{
//_logger.Error(ex);
}
return list;
}
public void Update(ConfigDbModel model)
{
try
{
string sql = @"REPLACE into configure(code,name,status,val,updatedate,updater,remark)
VALUES(@code,@name,@status,@val,@updatedate,@updater,@remark);";
using (SqliteConnection conn = new SqliteConnection(_connectionStr))
{
conn.Open();
conn.Execute(sql, model);
}
}
catch (Exception ex)
{
}
}
}
public class ConfigDbModel
{
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 代码
/// </summary>
public string Code { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 值
/// </summary>
public string Val { get; set; }
public int Status { get; set; }
public DateTime UpdateDate { get; set; }
public string Updater { get; set; } = "admin";
public string Remark { get; set; } = "";
}
开始我们的测试程序 :
DbProvider db = new DbProvider();
var configlist = db.GetConfigs();
if (configlist.Count > 0)
Console.WriteLine("获取配置成功!");
var config = db.GetConfig("NET_GPSPORT_1");
if(config!=null)
Console.WriteLine($"NET_GPSPORT_1 Val:{config.Val}");
Console.ReadKey();
提示源代码如下:链接:https://pan.baidu.com/s/1ipMqGDCj8egzro8MQ_8drA
关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com
庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力