Home >Database >Mysql Tutorial >C#连接mysql三种方式_MySQL
第一种方式:
使用MySQLDriverCS.dll连接
MySQLDriverCS软件下载:http://sourceforge.net/projects/mysqldrivercs/?source=typ_redirect
安装完之后再引用中添加引用,找到安装目录,找到MySQLDriverCS.dll文件,然后添加using MySQLDriverCS.dll文件
参考网址:http://www.bitsCN.com/kf/201401/272682.html
C#连接mysql代码
MySQLConnection DBConn; DBConn = new MySQLConnection(new MySQLConnectionString("10.99.19.121","haha", "root", "root", 3306).AsString); //DBConn = new MySQLConnection(new MySQLConnectionString("数据源","数据库名", "用户名", "密码", 端口号).AsString); try { DBConn.Open(); // 执行查询语句 MessageBox.Show("数据库已经连接了!"); string sql = "select * from tb_user"; MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn); DataSet ds = new DataSet(); mda.Fill(ds, "table1"); this.dataGridView1.DataSource = ds.Tables["table1"]; } catch(Exception ex) { MessageBox.Show(ex.Message); } DBConn.Close();
MySQLConnectionString constr = new MySQLConnectionString("10.99.19.121", "haha", "root", "root", 3306); MySQLConnection DBConn = new MySQLConnection(constr.AsString); //MySQLConnection DBConn; //DBConn = new MySQLConnection(new MySQLConnectionString("10.99.19.121","haha", "root", "root", 3306).AsString); try { DBConn.Open(); // 执行查询语句 MessageBox.Show("数据库已经连接了!"); string sql = "select * from tb_user"; MySQLDataAdapter mda = new MySQLDataAdapter(sql, DBConn); DataSet ds = new DataSet(); mda.Fill(ds, "table1"); this.dataGridView1.DataSource = ds.Tables["table1"]; } catch(Exception ex) { MessageBox.Show(ex.Message); } DBConn.Close();
string M_str_sqlcon = "server=10.99.19.121;user id=root;password=root;database=haha"; //根据自己的设置 MySqlConnection mycon = new MySqlConnection(); mycon.ConnectionString = M_str_sqlcon; try { mycon.Open(); MessageBox.Show("数据库已经连接了!"); string sql = "select * from tb_user"; MySqlDataAdapter mda = new MySqlDataAdapter(sql, mycon); DataSet ds = new DataSet(); mda.Fill(ds, "table1"); this.dataGridView1.DataSource = ds.Tables["table1"]; } catch(Exception ex) { MessageBox.Show(ex.Message); } mycon.Close();
通过ODBC访问mysql数据库
(没有时间研究那么多,之后会补充进来)
个人建议C#和sqlserver配合使用很好,但是和mysql不是说不好,只是不太合适,试想,你做一个项目,你还要给人家安装一个软件才能连接上数据库,感觉太麻烦,不专业,当然可以自己写一个库,但是很麻烦,而且又不是谁都会,所以个人建议用sqlserver,个人建议,不喜勿喷!!