Csharp Sqlite
Csharp Sqlite
title: csharp-sqlite
date: 2020-06-13 13:57:48
tags: csharp
categories: Language
---
## .net framework
#### dapper
```c#
public ObservableCollection<ModelConfig> m_config = new
ObservableCollection<ModelConfig>();
// 单个对象插入
public static int Insert(Person person)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
return connection.Execute("insert into Person(Name,Remark)
values(@Name,@Remark)", person);
}
}
// 批量插入
public static int Insert(List<Person> persons)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
return connection.Execute("insert into Person(Name,Remark)
values(@Name,@Remark)", persons);
}
}
// 删除
public static int Delete(Person person)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
return connection.Execute("delete from Person where id=@ID", person);
}
}
// 修改
public static int Update(Person person)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
return connection.Execute("update Person set name=@name where id=@ID",
person);
}
}
## .net core
## 添加 connection string
[sqlite-net](https://github.com/praeclarum/sqlite-net)
SQLite-Net Extensions is a very simple ORM that provides cascade operations, one-
to-one, one-to-many, many-to-one, many-to-many, inverse and text-blobbed
relationships on top of the sqlite-net library.
[SQLiteNetExtensions](https://www.nuget.org/packages/SQLiteNetExtensions/)
https://docs.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-
sqlite-orm
```c#
using SQLite;
## 查询
```c#
class model_coeff
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string name { get; set; }
public string comment { get; set; }
public string value { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.CascadeDelete)]
public List<Model_master_attribute> attributes { get; set; }
[OneToMany(CascadeOperations = CascadeOperation.CascadeDelete)]
public List<Model_master_preelaboration> preelaborations { get; set; }
}
try
{
long masterID = 0;
var items = App.conn.Query<Model_Measure_item>(sql, masterID);
m_coeffs.Clear();
var ret = App.conn.GetTableInfo("model_coeff");
if (0 == ret.Count)
{
App.conn.CreateTable<model_coeff>();
}
// 访问数据库
var query = App.conn.Table<model_coeff>();
foreach (var item in query)
{
m_coeffs.Add(item);
}
return m_coeffs;
}
catch (Exception ex)
{
MessageBox.Show("获取常量系数数据出现异常." + ex.Message);
Log.Error(ex, "Application start-up failed");
}
```
```c#
using System;
using System.Data.SQLite;
namespace RetrieveCars
{
class Program
{
static void Main(string[] args)
{
string cs = @"URI=file:C:\Users\Jano\Documents\test.db";
while (rdr.Read())
{
Console.WriteLine($"{rdr.GetInt32(0)} {rdr.GetString(1)}
{rdr.GetInt32(2)}");
}
}
}
}
```
### 参数化
```c#
var param1 = Convert.ToInt32(isUserApp).ToString();
var param2 = $"%{constraint.Trim()}%";
var packages = await conn.QueryAsync<Package>("SELECT * FROM Package WHERE UserApp
= ? AND Name LIKE ? ORDER BY Name COLLATE NOCASE ASC;", new string[2] { param1,
param2 });
```
### 排序
```c#
try
{
m_preelaboration.Clear();
var ret = App.conn.GetTableInfo("Model_preelaboration");
if (0 == ret.Count)
{
App.conn.CreateTable<Model_preelaboration>();
}
// 访问数据库
var query = App.conn.Table<Model_preelaboration>().OrderBy(x =>
x.MeasureStepId);
foreach (var item in query)
{
m_preelaboration.Add(item);
}
return m_preelaboration;
}
catch (Exception ex)
{
//TODO log here
MessageBox.Show("获取预运算数据出现异常." + ex.Message);
Log.Error(ex, "List_preelaboration failed");
}
// 访问数据库
var query = App.conn.Table<Model_log>().OrderByDescending(x => x.Time);
```
```c#
public Int64 Last_row_id()
{
var result = App.conn.QueryScalars<Int64>("SELECT last_insert_rowid()");
if (result.Count > 0)
{
return result[0];
}
else
{
return 0;
}
}
```
## 查看表是否存在
```c#
var ret = App.conn.GetTableInfo("model_coeff");
if (0 == ret.Count)
{
App.conn.CreateTable<model_coeff>();
}
```
## 修改表名称
```c#
var sql = $"ALTER TABLE Model_trade_diary RENAME TO Model_trade_diary_bak";
var winAmount = App.conn.Execute(sql);
```
## 插入
```c#
public int insert_coeff(model_coeff coeff)
{
try
{
// 访问数据库
var modified = App.conn.Insert(coeff);
return modified;
}
catch (Exception ex)
{
MessageBox.Show("保存系数数据出现异常." + ex.Message);
Log.Error(ex, "insert_coeff failed");
}
return 0;
}
// use transaction
var db = new SQLiteConnection(path);
db.RunInTransaction(() => {
// database calls inside the transaction
db.Insert(stock);
db.Insert(valuation);
});
```
## 更新
```c#
public int update_coeff(model_coeff coeff)
{
try
{
// 访问数据库
var modified = App.conn.Update(coeff);
return modified;
}
catch (Exception ex)
{
MessageBox.Show("获取常量系数数据出现异常." + ex.Message);
Log.Error(ex, "update_coeff failed");
}
return 0;
}
```
## 删除
```c#
public int delete_coeff(int id)
{
try
{
// 访问数据库
var modified = App.conn.Delete<model_coeff>(id);
return modified;
}
catch (Exception ex)
{
MessageBox.Show("删除常量系数数据出现异常." + ex.Message);
Log.Error(ex, "delete_coeff failed");
}
return 0;
}
## 数据模型忽略字段
```c#
[Table("my_tab")]
public class MyObj
{
[PrimaryKey, Column("column1")]
public string myObjField1 { get; set; }
[Column("column2")]
public string myObjField2 { get; set; }
[Ignore]
public string myObjField3 { get; set; }
}
```
## 关系模型,1 对多,多对多
[SQLiteNetExtensions](https://www.nuget.org/packages/SQLiteNetExtensions/)
[bitbucket](https://bitbucket.org/twincoders/sqlite-net-extensions/src/master/)
```c#
public class Model_master_duplicate_attribute
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
// 标准件特征名称
public string DuplicateAttrName { get; set; }
// 标准件特征描述
public string DuplicateAttrComment { get; set; }
// 标准件特征名义值
public string DuplicateAttrNominal { get; set; }
// 标准件特征单位
public string DuplicateAttrUnit { get; set; }
// 标准件特征实际值
public string DuplicateAttrTrueValue { get; set; }
// 标准件特征实际偏置
public string DuplicateAttrTrueOffset { get; set; }
// Model_master_duplicate 的主键
[ForeignKey(typeof(Model_master_duplicate))]
public Int64 masterDupID { get; set; }
// Model_master 的主键
[ForeignKey(typeof(Model_master))]
public Int64 masterID { get; set; }
// Model_master_attribute 的主键
[ForeignKey(typeof(Model_master_attribute))]
public Int64 masterAttrID { get; set; }
}
```