C#使用MySQLConnectorNet和MySQLDriverCS操作MySQL的方法


使用MySQLConnectorNet连接MySQL数据库
1.首先下载安装Connector/Net,http://www.mysql.com/downloads/connector/net/
并从安装目录中得到所需动态链接库MySql.Data.dll,如果已经有MySql.Data.dll也可以不用安装。

2.在项目中添加对该动态链接库的引用

3.在mySQL中建一些测试数据如:
我是使用phpAdmin

INSERT INTO stuinfo( first_name, last_name, Birthdate )  
VALUES ( 
'John', 'Smith', '1990-2-3' 
)  

static void Main(string[] args) 
    { 
      string url = "server=127.0.0.1;user=root;database=student;port=3306;password=root;";//指明要连接的数据库地址,用户名,数据库名,端口,密码 
      MySqlConnection conn = new MySqlConnection(url);//实例化连接 
      conn.Open();//打开连接 
 
      string sta = "select * from stuinfo";//执行一个简单的语句 
      MySqlCommand comm = new MySqlCommand(sta, conn); 
      MySqlDataReader reader = comm.ExecuteReader();//用MySqlDataReader接收执行结果 
      while (reader.Read()) 
      { 
        Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) +" " + reader.GetString(3));//读出查询的结果 
      } 
      Console.ReadKey(); 
      reader.Close(); 
      conn.Close();//关闭连接 
    } 

使用MySQLDriverCS连接MySQL数据库
与使用MySQLConnectorNet大同小异,首先下载安装MySQLDriverCS后得到动态链接库文件:
http://sourceforge.net/projects/mysqldrivercs/

将MySQLDriverCS.dll添加到工程的引用中:

还是利用上买呢已经在MySQL数据库中建立了的测试数据,所以直接编写C#代码:

static void Main(string[] args) 
    { 
      MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("127.0.0.1","student", "root", "root",3306).AsString); 
      conn.Open(); 
 
      MySQLCommand cmd = new MySQLCommand("select * from stuinfo", conn); 
      DbDataReader reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
        Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) + " " + reader.GetString(3));//读出查询的结果   
      } 
      Console.ReadKey(); 
      reader.Close(); 
      conn.Close();//关闭连接   
    } 

执行结果:

数据被成功读出。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3