web.config

<connectionStrings>
   <add name="MysqlDB" connectionString="Data Source=.;Initial Catalog=dbname;Persist Security Info=True;User ID=username;Password=password;" providerName="MySql.Data.MySqlClient" />
  </connectionStrings>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

namespace Service.Common
{
    public class DbMyHelp
    {   
        //连接字符串拼装  
        //mycon = new MySqlConnection("Host=127.0.0.1;UserName=root;Password=root;Database=score;Port=3306");
        //private static string config = System.Configuration.ConfigurationManager.AppSettings["MysqlDB"].ToString();
        private string config = string.Empty;
            /// <summary>
        /// 数据库连接串
        /// </summary>
        public string ConnectionString
        {
            set { config = value; }
        }

/// <summary>
        /// 构造
        /// </summary>
        public DbMyHelp(string connName)
        {
            this.config = System.Configuration.ConfigurationManager.ConnectionStrings[connName].ToString();
        }
        /// <summary>
        /// 查询返回List<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <returns></returns>
        public List<T> QueryList<T>(string sql)
        {
            ///////////////////获取MYSQ看数据返回值////////////////////////////  
            MySqlConnection mycon = new MySqlConnection(config);
            //连接  
            mycon.Open();
            //查询命令赋值,可以写多条语句,多条语句之间用;号隔开  
            MySqlCommand mycom = new MySqlCommand(sql, mycon);
            MySqlDataReader myrec = mycom.ExecuteReader();

List<T> list = new List<T>();
            //一次次读,读不到就结束  
            while (myrec.Read())
            {
                T obj = ExecDataReader<T>(myrec);
                list.Add(obj); //string   myInfo = myInfo + myrec["Name"] + " " + myrec["ID"];
            }
            //////关闭相关对象  
            myrec.Close();
            mycom.Dispose();
            mycon.Close();
            return list;

}
        /// <summary>
        /// 查询返回object
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public object QueryObject(string sql)
        {
            ///////////////////获取MYSQ看数据返回值////////////////////////////  
            MySqlConnection mycon = new MySqlConnection(config);
            //连接  
            mycon.Open();
            //查询命令赋值,可以写多条语句,多条语句之间用;号隔开  
            MySqlCommand mycom = new MySqlCommand(sql, mycon);
            object obj = mycom.ExecuteScalar();
            //////关闭相关对象  
            mycom.Dispose();
            mycon.Close();
            return obj;

}
        /// <summary>
        /// 查询返回datatable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable QueryTable(string sql)
        {
            MySqlConnection mycon = new MySqlConnection(config);
            mycon.Open();
            MySqlCommand mycom = new MySqlCommand(sql, mycon);
            DataSet dataset = new DataSet();//dataset放执行后的数据集合
            MySqlDataAdapter adapter = new MySqlDataAdapter(mycom);
            adapter.Fill(dataset);
            mycom.Dispose();
            mycon.Close();
            return dataset.Tables[0];
        }
        /// <summary>
        /// 操作增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExecutSql(string sql)
        {
            int result = 0;
            MySqlConnection mycon = new MySqlConnection(config);
            mycon.Open();
            MySqlCommand mycom = new MySqlCommand(sql, mycon);
            result = mycom.ExecuteNonQuery();
            mycom.Dispose();
            mycon.Close();
            mycon.Dispose();
            return result;

}
        /// <summary>
        /// 事务操作增删改
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int ExcuteTran(string sql)
        {
            MySqlConnection mycon = new MySqlConnection(config);
            MySqlCommand mycom = null;
            MySqlTransaction trans = null;
            int result = 0;
            try
            {
                mycon.Open();
                mycom = mycon.CreateCommand();
                mycom.CommandText = sql;

//创建事务  
                trans = mycon.BeginTransaction();
                result = mycom.ExecuteNonQuery();
                //事务提交  
                trans.Commit();
            }
            catch
            {
                //事务回滚  
                trans.Rollback();
            }
            finally
            {
                mycom.Dispose();
                mycon.Close();
                mycon.Dispose();
            }
            return result;
        }  
        /// <summary>
        /// IDataReader、MySqlDataReader 转T实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader"></param>
        /// <returns></returns>
        private T ExecDataReader<T>(IDataReader reader)
        {
            T obj = default(T);
            try
            {
                Type type = typeof(T);
                obj = (T)Activator.CreateInstance(type);//从当前程序集里面通过反射的方式创建指定类型的对象   
                PropertyInfo[] propertyInfos = type.GetProperties();//获取指定类型里面的所有属性
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        string fieldName = reader.GetName(i);
                        if (fieldName.ToLower() == propertyInfo.Name.ToLower())
                        {
                            //object val = reader[propertyInfo.Name];//读取表中某一条记录里面的某一列
                            object val = reader[fieldName];//读取表中某一条记录里面的某一列
                            if (val != null && val != DBNull.Value)
                            {
                                propertyInfo.SetValue(obj, val);
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return obj;
        }

}
    public static class DataHelper
    {
        /// <summary>
        /// DataTable 转List<T>实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> ToEntity<T>(this DataTable dt) where T : new()
        {
            List<T> list = new List<T>();
            Type info = typeof(T);
            var props = info.GetProperties();
            foreach (DataRow dr in dt.Rows)
            {
                T entity = new T();
                foreach (var pro in props)
                {
                    var propInfo = info.GetProperty(pro.Name);
                    if (dt.Columns.Contains(pro.Name))
                    {
                        propInfo.SetValue(entity, Convert.ChangeType(dr[pro.Name], propInfo.PropertyType), null);
                    }
                }
                list.Add(entity);
            }
            return list;
        }
    }
}

MYSQL连接数据库的更多相关文章

  1. navicat for mysql连接数据库报错1251

    使用Navicat for mysql 连接数据库,报如下错误 原因:数据库安装的是8.0版本,新的mysql采用了新的加密方式,导致连接失败 解决办法:数据库执行如下命令 改密码加密方式:用管理员身 ...

  2. Database学习 - mysql 连接数据库 库操作

    连接数据库 语法格式: mysql -h 服务器IP -P 端口号 -u用户名 -p密码 --prompt 命令提示符 --delimiter 指定分隔符 示例: mysql -h 127.0.0.1 ...

  3. MySql连接数据库和操作(java)

    package org.wxd.weixin.util; import java.sql.Connection;import java.sql.DriverManager;import java.sq ...

  4. MYSQL 连接数据库命令收藏

    一.MySQL 连接本地数据库,用户名为“root”,密码“123”(注意:“-p”和“123” 之间不能有空格) C:\>mysql -h localhost -u root -p123 二. ...

  5. mysql连接数据库p的大小写

    命令:mysql -uroot -p -hlocalhost -P3306 -h 用来指定远程主机的IP -P (大写) 用来指定远程主机MYAQL的绑定端口

  6. MySQL 连接数据库

    一.MySQL 连接本地数据库,用户名为“root”,密码“123”(注意:“-p”和“123” 之间不能有空格),缺点:密码显示在显示器上,容易泄露. C:\>mysql -h localho ...

  7. PHP MySQL 连接数据库 之 Connect

    连接到一个 MySQL 数据库 在您能够访问并处理数据库中的数据之前,您必须创建到达数据库的连接. 在 PHP 中,这个任务通过 mysql_connect() 函数完成. 语法 mysql_conn ...

  8. MySQL连接数据库报时区错误:java.sql.SQLException: The server time zone value

    连接MySQL数据库时报以下时区错误信息: java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized ...

  9. mysql连接数据库存报下面错误:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

    输入 mysql -u root 登录 mysql 的时候出现以下错误: ERROR 2002 (HY000): Can't connect to local MySQL server through ...

随机推荐

  1. Java笔记(十八)……包

    概述 对类文件进行分类管理. 给类提供多层命名空间. 写在程序文件的第一行. 类名的全称的是 包名.类名. 包也是一种封装形式. 访问权限 引用<The Complete Reference&g ...

  2. bzoj 1228 [SDOI2009]E&D(sg函数,找规律)

    Description 小E 与小W 进行一项名为“E&D”游戏.游戏的规则如下:桌子上有2n 堆石子,编号为1..2n.其中,为了方便起见,我们将第2k-1 堆与第2k 堆(1 ≤ k ≤ ...

  3. iOS开发——View的透明属性hidden、alpha、opaque

    Hidden.Alpha.Opaque的区别 在iOS中,每个View都有Hidden.Alpha.Opaque三个关于透明的属性,官方文档介绍如下: 1. @property(nonatomic) ...

  4. Esper系列(十一)NamedWindow语法Merge、Queries、Indexing、Dropping

    On-Merge With Named Windows 功能:对window中的insert.update.delete操作进行组合运用. 格式: 1  "; 14      15  Sys ...

  5. 解决 Provider 'System.Data.SqlServerCe.3.5' not installed. -摘自网络

    在64位机器上开发,如果使用到SqlServerCe的话,那么很可能会碰到这个问题,问题有两个方面: 1.如提示所云,没有安装SqlServerCe,只要去微软下载就好了. 2.系统已经安装SqlSe ...

  6. vim 设置 swap file, 防止 同一个文件同时被多次打开,而且有恢复的功效

    在.vimrc里加入:   set swapfile   即可以使能swap file, swapfile的名字一般是      .filename.swp    (如     .doc.txt.sw ...

  7. IP头部校验(转)

    一:原理 当发送IP包时,需要计算IP报头的校验和: 1.把校验和字段置为0: 2.对IP头部中的每16bit进行二进制求和: 3.如果和的高16bit不为0,则将和的高16bit和低16bit反复相 ...

  8. eclipse安装插件checkstyle

    最近听说了一个eclipse神器:checkstyle,可以帮助java开发人员规范代码,对我这种有代码洁癖的人来说,这有着不小的魔力啊,必然要安装试一试啊. 我最喜欢的安装方式是 输入一个安装网址, ...

  9. T-SQL语句查看作业等信息

    因服务器需要迁移,需要将现有JOB迁移至新服务器,待服务器调整完毕,则重新迁移到原服务器,所以在做迁移之前希望将现有JOB进行备份,不至于乱了执行时间.1.查看所有作业列表USE master SEL ...

  10. iOS开发中懒加载的使用和限制

    1.在开发过程中很多时候,很多控件和对象需要alloc为了,提高开发效率使得懒加载得以产生. 2.下边用代码解释: - (NSMutableArray *)newsArr{ if (!_newsArr ...