从MySQL获取数据

安装

PM> install-package newtonsoft.json

PM> install-package mysql.data

string connectionString = "Server=192.168.97.111;Database=testdb;Uid=root;Pwd=Passw0d;Port=3306"

代码

string connectionString = "Server=127.0.0.1;Database=testdb;Uid=root;Pwd=123456;Port=3306";


string cmdText = "SELECT Id,Name FROM abcTable";

        public static T[] QueryTable<T>(string commandText, params MySqlParameter[] commandParameters)
        {
            var dataset = MySql.Data.MySqlClient.MySqlHelper.ExecuteDataset(connectionString, commandText, commandParameters);
            if (dataset.Tables.Count == 1)
            {
                return JsonConvert.DeserializeObject<T[]>(JsonConvert.SerializeObject(dataset.Tables[0]));
            }
            return new T[0];
        }
View Code

测试代码

 

class MyClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


var aa = QueryTable<MyClass>(cmdText, null);
View Code

 

posted @ 2016-01-15 15:49  joe62  阅读(444)  评论(0编辑  收藏  举报