下载驱动安装:mysql-connector-net-6.7.4.msi
从visual studio 2010 中“添加引用”将C:\Program Files (x86)\MySQL\MySQL Connector Net 6.7.4\Assemblies\v4.5\MySql.Data.dll加入,再在类中加入using Mysql.Data.MySqlClient
using System;
using MySql.Data.MySqlClient;
class DBConnection
{
public void connection ()
{
//定义连接字符串
string url = "server=127.0.0.1;user=root;database=cwgl;password=123456;";
//定义连接对象sConn
MySqlConnection sConn = new MySqlConnection(url);
try{
//打开连接
sConn.Open();
Console.WriteLine("连接成功");
}
catch(Exception ex)
{ //给出错误信息
Console.WriteLine("连接错误:"+ex.Message);
}
/**查询数据**/
/*
string sta = "select * from cwgl_user";//执行一个简单的语句
MySqlCommand comm = new MySqlCommand(sta, sConn);
MySqlDataReader reader = comm.ExecuteReader();//用MySqlDataReader接收执行结果
while (reader.Read())
{
Console.WriteLine(reader.GetString(0) + " " + reader.GetString(1) + " " + reader.GetString(2) );//读出查询的结果
}
reader.Close();
/**查询数据**/
string sta = "insert into cwgl_user(user_name,user_password) values('liuyingjie','123456')";
//string sta = "delete from cwgl_user where user_name='刘英杰'";
MySqlCommand comm = new MySqlCommand(sta,sConn);
comm.ExecuteNonQuery();
//关闭数据库连接
sConn.Close();
}
}