c#远程连接mysql数据库

1、首先我使用mysqlconnection方法连接数据库,因此需要下载MySQLDriverCS,网址(http://sourceforge.net/projects/mysqldrivercs/)

,安装好后,将MySQLDriverCS.dll通过添加引用的方式,添加到项目中。

2、设置mysql数据库为允许远程访问,采用如下代码:

格式:grant 权限 on 数据库名.表名 用户@登录主机 identified by "用户密码";
grant select,update,insert,delete on *.* to 'root'@'192.168.0.1' identified by "123456";
  
    查看结果,执行:
   use mysql;
   select host,user,password from user;
将host字段的值改为%就表示在任何客户端机器上能以xuys用户登录到mysql服务器,建议在开发时

设为%。 

 
3、下面是具体的数据库操作代码:

 using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; using MySQLDriverCS; namespace DB { class DB { private MySQLConnection conn; private MySQLCommand cmd; private MySQLDataAdapter da; public DB() { // // TODO: 在此处添加构造函数逻辑 // this.conn = new MySQLConnection(new MySQLConnectionString("10.214.59.106", "dt", "root", "123456").AsString); this.cmd = new MySQLCommand(); this.da = new MySQLDataAdapter(); } //返回数据表 public DataTable QeuryTable(string sqlTxt) { DataTable dt = new DataTable(); try { this.conn.Open(); this.cmd.CommandText = sqlTxt; this.cmd.Connection = this.conn; this.da.SelectCommand = this.cmd; this.da.Fill(dt); } catch (SqlException ex) { throw ex; } finally { this.conn.Close(); } return dt; } public DataSet QeuryDataSet(string sqlTxt) { DataSet ds = new DataSet(); try { this.conn.Open(); this.cmd.CommandText = sqlTxt; this.cmd.Connection = this.conn; this.da.SelectCommand = this.cmd; this.da.Fill(ds); } catch (SqlException ex) { throw ex; } finally { this.conn.Close(); } return ds; } public int ExecuteNonQuery(string sqlTxt) { int i = 0; try { this.conn.Open(); this.cmd.CommandText = sqlTxt; this.cmd.Connection = this.conn; i = this.cmd.ExecuteNonQuery(); } catch (SqlException ex) { throw ex; } finally { this.conn.Close(); } return i; } } }

你可能感兴趣的:(c#远程连接mysql数据库)