Dapper配置 MySQL连接

在nugget包管理器中安装Dapper包
1.连接MySQL:nugget安装MySQL.Data包。
在appsetting中配置数据库链接:

  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;port=端口;database=数据库名字;SslMode=None;uid=用户名;pwd=密码;Allow User Variables=true"
  },

新建BaseRepository类,用于连接数据库:

public class BaseRepository : IDisposable
    {
        public static IConfigurationRoot Configuration { get; set; }

        private  static MySqlConnection conn;

        public static MySqlConnection GetMySqlConnection(bool open = true,
        bool convertZeroDatetime = false, bool allowZeroDatetime = false)
        {
            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
            var cs = builder.GetSection("ConnectionStrings:DefaultConnection").Value;
            var csb = new MySqlConnectionStringBuilder(cs)
            {
                AllowZeroDateTime = allowZeroDatetime,
                ConvertZeroDateTime = convertZeroDatetime
            };
            conn = new MySqlConnection(csb.ConnectionString);
            return conn;
        }
        public void Dispose()
        {
            if (conn != null && conn.State != System.Data.ConnectionState.Closed)
            {
                conn.Close();
            }
        }
    }

现在可以在其他地方使用SQL语句了
查询数据:

using (IDbConnection connection = BaseRepository.GetMySqlConnection())
{
     return connection.Query<User>(sql).ToList();
}
//对应的model
public class User
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string Url { get; set; }
    public int Age { get; set; }
}

注意:如果不是.netcore的web项目,IConfigurationRoot和ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”).Build();部分会报错,需要下载三个包:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Binder
VS2019会 提示下载第一个包,但是下载后没有后面两个包,AddJsonFile(“appsettings.json”).Build();部分会报错

你可能感兴趣的:(Dapper配置 MySQL连接)