SqlSugar Database Connection Guide

One common way to connect to a database using SqlSugar is by creating a SqlSugarClient object, specifying the connection string, and then using methods of the object to interact with the database. Here is an example code:

using SqlSugar;

public class DatabaseHelper
{
    private SqlSugarClient Db;

    public DatabaseHelper()
    {
        string connectionString = "Server=127.0.0.1;Database=mydatabase;Uid=root;Pwd=mypassword;";
        Db = new SqlSugarClient(new ConnectionConfig
        {
            ConnectionString = connectionString,
            DbType = DbType.MySql,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
    }

    public List<User> GetUsers()
    {
        List<User> users = Db.Queryable<User>().ToList();
        return users;
    }

    public void AddUser(User user)
    {
        Db.Insertable(user).ExecuteCommand();
    }
}

public class User
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

In the previous example, we created a DatabaseHelper class which includes a SqlSugarClient object for connecting to the database. We also defined a User class to represent the user table in the database. By calling methods of the DatabaseHelper class, we can query user data or insert new user data into the database.

bannerAds