VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • MySql查询数据

引用的DLL

1
2
MySql.Data.MySqlClient
System.Data

City实体

1
2
3
4
5
6
7
8
public class City
{
    public int ID { getset; }
    public string Name { getset; }
    public string CountryCode { getset; }
    public string District { getset; }
    public int Population { getset; }
}

连接字符串

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

实现逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}


相关教程