Use SqlSugar to connect multiple databases (sqlserver, sqlite, mysql)

    Sometimes, a project has only one database, such as only SQLite, or MySQL database, then we only need to use a fixed database. But if a project is written and used by multiple users, but multiple users use different databases, at this time, we need to design the software in a mode that can connect to multiple databases, and configure which database to use. Can.

This example uses

sqlserver

mysql

SQLite

1. Create a wpf program, using .net5

2. Install SqlSugar

3. Create HelperDB

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarDemo
{
    public static class HelperDB
    {
        public static SqlSugarClient SqlSugarClient
        {
            get
            {
                return new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SetDBType(ConfigurationManager.AppSettings["DBType"]), //配置数据库类型
                    ConnectionString = ConfigurationManager.AppSettings["ConnectionString"],  //数据库连接字符串
                    IsAutoCloseConnection = true,//设置为true无需使用using或者Close操作,自动关闭连接,不需要手动关闭数据链接
                    InitKeyType = InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息
                });
            }
        }
        public static DbType SetDBType(string dbType)
        {
            DbType DBType;
            switch (dbType.ToLower())
            {
                case "sqlserver":
                    DBType = DbType.SqlServer;
                    break;
                case "sqlite":
                    DBType = DbType.Sqlite;
                    break;
                case "mysql":
                    DBType = DbType.MySql;
                    break;
                default:
                    DBType = DbType.MySql;
                    break;
            }
            return DBType;
        }
    }
}

4.Users entity class, this entity class should be the same as the database, forming a one-to-one relationship.

database

Here, we have a database first, and then manually create entity classes. You can also use the SqlSugar toolbox or code to automatically generate entity classes

Db First Entity Generation - SqlSugar 5x - .NET Fructose

the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarDemo
{
    public class Users
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int age { get; set; }

        public string aa { get; set; }
        public string bb { get; set; }
    }
}

5. MainWindow.xaml interface

<Window x:Class="SqlSugarDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SqlSugarDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="btn" Content="确定" Click="btn_Click" Width="100" Height="50"/>
    </Grid>
</Window>

6. MainWindow.cs interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SqlSugarDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            List<Users> users = HelperDB.SqlSugarClient.Queryable<Users>().Where(c => c.Name == "张三").ToList();
        }
    }
}

7. Modify the App.config configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--<add key="DBType" value="sqlserver" />
    <add key="ConnectionString" value="server=192.168.20.245;uid=sa;pwd=123456;database=mysqlCodeFirst" />-->

    <add key="DBType" value="mysql" />
    <add key="ConnectionString" value="server=localhost;Database=mysqlCodeFirst;Uid=root;Pwd=123456" />
  </appSettings>
</configuration>

8. We open the MySQL database, and then debug to see the results of the program

The value of the table in the database

9. We modify the configuration and replace it with a SqlServer database

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="DBType" value="sqlserver" />
    <add key="ConnectionString" value="server=192.168.20.245;uid=sa;pwd=123456;database=mysqlCodeFirst" />

    <!--<add key="DBType" value="mysql" />
    <add key="ConnectionString" value="server=localhost;Database=mysqlCodeFirst;Uid=root;Pwd=123456" />-->
  </appSettings>
</configuration>

10. Start the SqlServer database, and then debug to see the results of the program

The value of the table in the database

11. Sqlite database, you need to create a database in the code, create a table, and then create data

configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--<add key="DBType" value="sqlserver" />
    <add key="ConnectionString" value="server=192.168.20.245;uid=sa;pwd=123456;database=mysqlCodeFirst" />-->

    <!--<add key="DBType" value="mysql" />
    <add key="ConnectionString" value="server=localhost;Database=mysqlCodeFirst;Uid=root;Pwd=123456" />-->
    
    <add key="DBType" value="sqlite" />
    <add key="ConnectionString" value="DataBase\test.db" />
  </appSettings>
</configuration>

HelperDB class files 

using Microsoft.Data.Sqlite;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlSugarDemo
{

    public static class HelperDB
    {
        public static string DBConnectionString { get; set; } = ConfigurationManager.AppSettings["ConnectionString"];
        public static SqlSugarClient SqlSugarClient
        {
            get
            {
                return new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SetDBType(ConfigurationManager.AppSettings["DBType"]), //配置数据库类型
                    ConnectionString = DBConnectionString,  //数据库连接字符串
                    IsAutoCloseConnection = true,//设置为true无需使用using或者Close操作,自动关闭连接,不需要手动关闭数据链接
                    InitKeyType = InitKeyType.Attribute//默认SystemTable, 字段信息读取, 如:该属性是不是主键,是不是标识列等等信息
                });
            }
        }
        public static DbType SetDBType(string dbType)
        {
            DbType DBType;
            switch (dbType.ToLower())
            {
                case "sqlserver":
                    DBType = DbType.SqlServer;
                    break;
                case "sqlite":
                    DBType = DbType.Sqlite;
                    DBConnectionString = @"DataSource=" + AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["ConnectionString"];
                    //DBConnectionString = new SqliteConnectionStringBuilder()
                    //{
                    //    DataSource = @"E:\project\测试\SqlSugarDemo\bin\Debug\net5.0-windows\1.db" ,
                    //    Password = "123456"  //高版本不支持密码,需要低版本
                    //}.ToString();
                    break;
                case "mysql":
                    DBType = DbType.MySql;
                    break;
                default:
                    DBType = DbType.MySql;
                    break;
            }
            return DBType;
        }
    }
}

MainWindow.cs folder

using Microsoft.Data.Sqlite;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SqlSugarDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            HelperDB.SqlSugarClient.DbMaintenance.CreateDatabase();   //建库
            HelperDB.SqlSugarClient.CodeFirst.InitTables<Users>();    //建表

            Users users1 = new Users();
            users1.Id = 1;
            users1.Name = "张三";
            users1.age = 20;
            users1.aa = "111";
            users1.bb = "sqlite";
            HelperDB.SqlSugarClient.Insertable(users1).ExecuteCommand();  //插入数据

            var users = HelperDB.SqlSugarClient.Queryable<Users>().Where(c => c.Name == "张三").ToList();   //查询数据
        }
    }
}

The value of the table in the database

value for code debugging 

Guess you like

Origin blog.csdn.net/u012563853/article/details/127013521