C#连接操作MySQL数据库详细步骤 帮助类等(二次改进版)

 

 

 

 

最近准备写一个仓库管理的项目

  客户要求使用C#编写MySQL存储数据

  为了方便,整理了数据库操作的工具类

 

首先在项目App.config 文件下添加节点

  <connectionStrings>
    <add name="constr" connectionString="server=localhost;port=3306;user id=root;password=root;database=car;Charset=utf8;"/>
  </connectionStrings>

 


例如:

 

 然后在项目引用中添加MySQL.DAL.dll  类库

 

 

 

 

vs版本低的可能找不到这个类库,,只有去网上下载,然后添加本地引用了

 

 

然后编写工具类:

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

/// <summary>
/// @author: 房上的猫
/// 
/// @博客地址: https://www.cnblogs.com/lsy131479/
/// </summary>

namespace WMS.DAL
{
    public class MySQLDBHelp
    {
        public static string Constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

        #region  建立MySql数据库连接
        /// <summary>
        /// 建立数据库连接.
        /// </summary>
        /// <returns>返回MySqlConnection对象</returns>
        public MySqlConnection getMySqlCon()
        {
            string M_str_sqlcon = Constr;// "server=localhost;port=3306;user id=root;password=root;database=car"; //根据自己的设置
            MySqlConnection myCon = new MySqlConnection(M_str_sqlcon);
            return myCon;
        }
        #endregion

        #region  执行MySqlCommand命令
        /// <summary>
        /// 执行MySqlCommand
        /// </summary>
        /// <param name="M_str_sqlstr">SQL语句</param>
        public int getMySqlCom(string M_str_sqlstr, params MySqlParameter[] parameters)
        {
            MySqlConnection mysqlcon = this.getMySqlCon();
            mysqlcon.Open();
            MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
            mysqlcom.Parameters.AddRange(parameters);
            int count = mysqlcom.ExecuteNonQuery();
            mysqlcom.Dispose();
            mysqlcon.Close();
            mysqlcon.Dispose();
            return count;
        }
        #endregion

        #region  创建MySqlDataReader对象
        /// <summary>
        /// 创建一个MySqlDataReader对象
        /// </summary>
        /// <param name="M_str_sqlstr">SQL语句</param>
        /// <returns>返回MySqlDataReader对象</returns>
        public DataTable getMySqlRead(string M_str_sqlstr, params MySqlParameter[] parameters)
        {
            MySqlConnection mysqlcon = this.getMySqlCon();
            mysqlcon.Open();
            MySqlCommand mysqlcom = new MySqlCommand(M_str_sqlstr, mysqlcon);
            mysqlcom.Parameters.AddRange(parameters);
            MySqlDataAdapter mda = new MySqlDataAdapter(mysqlcom);
            DataTable dt = new DataTable();
            mda.Fill(dt);
            mysqlcon.Close();
            return dt;
        }
        #endregion
    }
}

 

 

 

进行测试:

 class Program
    {
        static void Main(string[] args)
        {
            MySQLDBHelp help = new MySQLDBHelp();
        
            String sql = "select * from insertcar";
            MySqlDataReader dr = help.getmysqlread(sql);
            while (dr.Read())
            {
                Console.WriteLine(dr["tax"].ToString());
            }
    
            Console.Read();
        }
    }

结果:

 

最后提供一个利用反射和泛型       可以将datatable  转为 list集合的工具类

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WMS.Common
{
   public class MyTool
    {
        /// <summary>
        /// DataSetToList
        /// </summary>
        /// <typeparam name="T">转换类型</typeparam>
        /// <param name="dataSet">数据源</param>
        /// <param name="tableIndex">需要转换表的索引</param>
        /// <returns></returns>
        public List<T> DataTableToList<T>(DataTable dt)
        {
            //确认参数有效
            if (dt == null )
                return null;

         

            List<T> list = new List<T>();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance<T>();
                //获取对象所有属性
                PropertyInfo[] propertyInfo = _t.GetType().GetProperties();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    foreach (PropertyInfo info in propertyInfo)
                    {
                        //属性名称和列名相同时赋值
                        if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
                        {
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                info.SetValue(_t, dt.Rows[i][j], null);
                            }
                            else
                            {
                                info.SetValue(_t, null, null);
                            }
                            break;
                        }
                    }
                }
                list.Add(_t);
            }
            return list;
        }
    }
}

 

posted @ 2018-06-23 10:48  房上的猫  阅读(23352)  评论(0编辑  收藏  举报