返回顶部

MySql数据库封装MySqlDBHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Newtonsoft.Json;
using MySql.Data.MySqlClient;


namespace DAL
{
    public class MySqlDBHelper
    {
        private  MySqlConnection GetConnection()
        {
            return new MySqlConnection("server=127.0.0.1;uid=root;pwd=root;database=mmmm");
        }


        public int ExecuteNonQuery(string sql)
        {
            int result = 0;
            using (MySqlConnection con = GetConnection())
            {
                con.Open();
                MySqlCommand scom = new MySqlCommand(sql, con);
                result =scom.ExecuteNonQuery();
                con.Close();
            }
            return result;
        }


        public DataTable ExecuteQuery(string sql)
        {
            DataTable dt = new DataTable();
            using (MySqlConnection con = GetConnection())
            {
                MySqlCommand scom = new MySqlCommand(sql, con);
                MySqlDataAdapter ada = new MySqlDataAdapter(scom);
                ada.Fill(dt);
            }
            return dt;
        }


        public List<T> ExecuteQueryList<T>(string sql)
        {
            DataTable dt = ExecuteQuery(sql);
            string json = JsonConvert.SerializeObject(dt);
            return JsonConvert.DeserializeObject<List<T>>(json);
        }
    }
}

 

posted @ 2019-04-01 19:33  世界欠绘梨衣一场婚礼  阅读(170)  评论(0编辑  收藏  举报