C#/c#

[ c# ] Dapper 사용해서 mysql select , insert

code094 2022. 12. 24. 12:15
 public class TestResultDTO
    {
        public int id { get; set; }
        public string name { get; set; }
        public float score { get; set; }
    }
public class Dapper
    {
        private MySqlConnection db = new MySqlConnection("Server=serverip;User=user;Password=password;Database=db_name;Port=port");
        public Dapper()
        {
            db.Open();

        }
        public TestResultDTO DapperSelect(string data)
        {
            if (db.State != System.Data.ConnectionState.Open) db.Open();

            string sql = "select id, name, score from table_name where score >= 90.5";
            TestResultDTO output = db.Query<TestResultDTO>(sql);

            return output; 

        }
        public void DapperInsert(TestResultDTO result)
        {
            string insertQuery = "INSERT INTO table_name(id,name,score) " +
                "VALUES(@id,@name,@score)";

            db.Execute(insertQuery, result);
        }
    }

사용전 mysqlconnector 와 dapper 를 Nuget 패키지 로 설치함 

 

dapper 사용시 주의해야 할 점은 db 컬럼명과 TestResultDTO 클래스의 필드명이 동일해야 한다는 점