winform中使用SqlSugar和SQLite

winform虽然是老古董了,但是在开发桌面方面,还是得心应手的,比如开发一个小工具,小demo之类的。接下来,我们使用SqlSugar和SQLite数据库,在winform中运用。

1.首先建立一个程序

2.安装 System.Data.SQLite,版本1.0.116

3.安装SqlSugar,版本5.0.0

4.增加SqlSugarHelper,关联1.db数据库

数据库创建:

1.我们可以使用Navicat,直接创建数据库

2.随便向表中增加一些数据 

别忘记把1.db复制到bin文件夹下面了

 然后下面关联上1.db数据库

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApp1
{
    public class SqlSugarHelper
    {
        static string url1 = AppDomain.CurrentDomain.BaseDirectory;
        // public static string ConnectionString = ; //必填, 数据库连接字符串
        public static SqlSugarClient db
        {
            get => new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = $"Data Source={url1}/1.db",
                DbType = SqlSugar.DbType.Sqlite,         //必填, 数据库类型
                IsAutoCloseConnection = true,       //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                InitKeyType = InitKeyType.SystemTable    //默认SystemTable, codefist需要使用Attribute
            });
        }
    }
}

5.在界面上面放一个按钮,在按钮下面写代码

6.代码,使用sql语句查询

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = SqlSugarHelper.db.Ado.GetDataTable("SELECT * FROM a");
        }
    }
}

7.使用实体类查询,首先要建立一个实体类

8.使用实体类查询

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = SqlSugarHelper.db.Ado.GetDataTable("SELECT * FROM a");

            var a = SqlSugarHelper.db.Queryable<a>().ToList();
        }
    }
}

9.效果

可见SqlSugar的,既能使用sql语句,还能使用实体类查询,想用什么就用什么,非常的方便自由。

猜你喜欢

转载自blog.csdn.net/u012563853/article/details/128357765