C#查询和遍历mysql表数据
using System;
using MySql.Data.MySqlClient;

namespace Mysql_Conn
{
    class Program
    {
        static void Main(string[] args)
        {
            string conStr = "server=127.0.0.1;port=3306;database=chicai_note;user=root;password=";
            MySqlConnection conn = new MySqlConnection(conStr);
            try
            {
                conn.Open();
                string sql = "select * from chicai_config";//要执行的sql语句
                MySqlCommand com = new MySqlCommand(sql,conn);//利用MysqlCommand创建命令
                MySqlDataReader reader = com.ExecuteReader();//查询多条数据用的
                while (reader.Read()) {//一行行进行读取
                    Console.WriteLine(reader[0].ToString() + reader.GetString("name").ToString());
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            Console.ReadKey();
        }
    }
}

MysqlCommand类含有执行不同类型的sql的方法,其中ExecuteReader()是读取多行结果的。可以通过MysqlDataReader的索引方式和Get***()方法传递字段的方式来获取当前行的列数据。


首页 我的博客
粤ICP备17103704号