码迷,mamicode.com
首页 > 数据库 > 详细

MySql查询数据

时间:2020-07-03 00:37:35      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:count   数据   select   sql查询   har   list   ndt   tostring   dataset   

引用的DLL

MySql.Data.MySqlClient
System.Data

City实体

    public class City
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string CountryCode { get; set; }
        public string District { get; set; }
        public int Population { get; set; }
    }

连接字符串

string connectionStr = "server=127.0.0.1;database=数据库;User ID=root;password=密码";

实现逻辑

        public List<City> GetCityList()
        {
            List<City> cityList = new List<City>();
            string sqlStr = "select * from city";
            using (MySqlConnection con = new MySqlConnection(connectionStr))
            {
                con.Open();
                MySqlCommand command = new MySqlCommand();
                if (con.State != ConnectionState.Open)
                {
                    con.Open();
                }
                command.Connection = con;
                command.CommandText = sqlStr;
                using (MySqlDataAdapter da = new MySqlDataAdapter(command))
                {
                    DataSet ds = new DataSet();
                    da.Fill(ds, "city");
                    foreach (DataRow inst in ds.Tables[0].Rows)
                    {
                        City city = new City();
                        city.ID = int.Parse(inst["ID"].ToString());
                        city.Name = inst["Name"].ToString();
                        city.CountryCode = inst["CountryCode"].ToString();
                        city.District = inst["District"].ToString();
                        city.Population = int.Parse(inst["Population"].ToString());
                        cityList.Add(city);

                    }
                }
            }
            return cityList;
        }

  

MySql查询数据

标签:count   数据   select   sql查询   har   list   ndt   tostring   dataset   

原文地址:https://www.cnblogs.com/HYJ0201/p/13227882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!