使用SqlSugar来操作数据库,这里以操作sqlLite为例来进行讲解,可以操作MySQL等数据库。
方法步骤:
1、使用NuGet下载类库SqlSugar
2、使用NuGet下载类库System.Data.SQLite
3、使用SQLiteStudio建立数据库和表单,如下图
4、在程序项目中建立文件夹Models并创建类SysAdmin,如下图
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VisionAssistant.Models
{
public class SysAdmin
{
public int LoginID { get; set; }
public string LoginName { get; set; }
public string LoginPwd { get; set; }
public int Role { get; set; }
}
}
5、在程序项目中创建类SqlSugarHelper,来进行操作数据库,代码如下
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VisionAssistant.Data
{
public class SqlSugarHelper
{
public SqlSugarClient db;
public SqlSugarHelper(string connectionString)
{
db = new SqlSugarClient(
new ConnectionConfig()
{
ConnectionString = connectionString,
DbType = DbType.Sqlite, //设置数据库类型
IsAutoCloseConnection = true, //自动释放数据务,如果存在事务,在事务结束后释放
InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
}
);
}
}
}
6、调用使用代码示例
using AutomaticMotionDAL;
using AutomaticMotionModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControlTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlSugarHelper sqlSugarHelper;
private void Form1_Load(object sender, EventArgs e)
{
//
string path = @"C:\Users\y\source\repos\YUEControl\ControlTest\bin\Debug\DataBase\AutomaticStoreMotion";
string connectionstring = "Data Source=" + path + ";Version=3;Pooling=False;Max Pool Size=100;";
sqlSugarHelper = new SqlSugarHelper(connectionstring);
}
private void button1_Click(object sender, EventArgs e)
{
var list= sqlSugarHelper.db.Queryable<SysAdmin>().ToList();
dataGridView1.DataSource = list;
}
}
}
这样就可以获取数据库里的内容了。
7、sqlsugar也可以操作数据库获取DataSet数据,执行sql语句
见链接执行SQL - SqlSugar 4.x - .NET果糖网 (donet5.com)
使用范例
DataSet alarmDs = Configure.Instance.sqlSugarHelper.db.Ado.GetDataSetAll("SELECT * FROM SysAdmin");
这样既可以获取DataSet的数据。更多详细的可以参考链接