ORM框架SqlSugar安装及使用(连接MySql)

一、安装

        通过NuGet包管理器搜索SqlSugar、MySql.Data、Newtonsoft.Json三个包并安装。

二、使用

1、获取连接字符串

示例代码:

        public static string GetConStr()
        {
            var builder = new MySqlConnectionStringBuilder()
            {
                Server = "localhost",
                UserID = "root",
                Password = "123456",
                Database = "test"
            };
            return builder.ConnectionString;
        }

2、获取一个SqlSugarClient实例

示例代码:

        public static SqlSugarClient GetSql()
        {
            string _connectstr = GetConStr();
            SqlSugarClient _client = new (new ConnectionConfig
            {
                ConnectionString = _connectstr,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
            return _client;
        }

3、构建一个表模型(名字不同,可通过SugarTable特性指定表)

示例代码:

    [SugarTable("teacher")]
    class Student
    { 
        public int ID { get; set; }
        public string Name { get; set; }        
    }

 4、使用SqlSugar框架命令操作数据库(增删改查)

示例代码:

        public static void Main()
        {
            SqlSugarClient client = GetSql();
            try
            {
                client.Ado.CheckConnection();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            //SqlSugarClient?  myclient= GetSqlSugarClient;
            Student stu = new() { ID = 2, Name = "lisi" };
            //var res = client.Queryable().Where(it => (it.ID.Equals(stu.ID))&&it.Name=="刘老师").First();
            var res = client.Queryable().Where(it =>it.Name.Contains("老师")).First();
            //var res = client.Queryable().First(it => (it.ID.Equals(stu.ID)) && it.Name == stu.Name);
            Console.WriteLine(res.Name);
            List res2=client.Queryable().ToList();
            foreach (Student student in res2)
                Console.WriteLine(student.Name);
        }

你可能感兴趣的:(mysql,数据库,c#)