.Net Core 连接MySQL 原生MySQL语句 Dapper

安装必要的依赖项

>PM Install-Package MySql.Data -Version 8.0.23
>PM Install-Package Dapper -Version 2.0.78

传送门.MySql.Data
传送门.Dapper

代码


using Dapper;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace Test.API.Queries
{
    public class TestQueries // : ITestQueries
    {

        private string _connectionString = string.Empty;

        public TestQueries(string constr)
        {
            _connectionString = !string.IsNullOrWhiteSpace(constr) ? constr : throw new ArgumentNullException(nameof(constr));
        }


        public async Task<IList<TestDTO>> GetChatDataMessageFilesNoSavedAsync()
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                connection.Open();

                var result = await connection.QueryAsync<TestDTO>
                (
                   @"SELECT '1' AS Id,'张三' AS UserName"
                );

                if (result.AsList().Count == 0)
                    throw new KeyNotFoundException();

                return result.AsList();
            }
        }
    }
	
	public class TestDTO
	{
		public int Id {get;set;}
		public string UserName {get;set;}	
	}
}

var queries = new TestQueries("Server=127.0.0.1;port=3306;Database=test_db;Uid=root;Pwd=123456;Allow User Variables=True;sslMode=None;Character Set=utf8;");

var result = queries.GetChatDataMessageFilesNoSavedAsync().Result;

posted @ 2021-04-20 08:58  zh89233  阅读(261)  评论(0编辑  收藏  举报