C#访问MySQL数据库的方法
(1)首先需要下载C#访问MySQL数据库的ADO.NET驱动程序
下载地址为:
http://dev.mysql.com/downloads/connector/net/6.0.html
我下载的版本为: mysql-connector-net-6.3.8.msi
下载地址如下url:
http://dev.mysql.com/downloads/mirror.php?id=405442
(2)安装mysql-connector-net
然后直接在Windows操作系统安装 mysql-connector-net-6.3.8.msi
默认是安装在C盘:
C:\Program Files\MySQL\MySQL Connector Net 6.3.8\Assemblies
v2.0
v4.0
安装完后我选择的是v2.0版本的
然后在应用工程中引用组件MySQL.Data.dll
(3)封装数据库访问组件DbConnectionMySQL
(4)客户端访问测试开发实例
- public void TestCShape_MySQL()
- {
- string constr = "server=localhost;User Id=root;password=root;Database=xp_users";
- DbConnectionWrapper dbw = new DbConnectionMySQL(constr);
- bool rbc=dbw.TestConnection();
- this.Context.Response.Write(rbc);
-
-
- string x = "";
-
- x = "delete from xp_users";
- if (dbw.ExecuteQuery(x) > 0)
- {
- this.Context.Response.Write("删除语句成功!下面是SQL语句<br>" + x);
- }
-
- x = "insert into xp_users(gid,uid,uname,sex,email,pwd) values(‘";
- x += "1‘,‘hsg77‘,‘何XXX‘,1,‘hsg77@163.com‘,‘1‘)";
- if (dbw.ExecuteQuery(x) > 0)
- {
- this.Context.Response.Write("插入语句成功!下面是SQL语句<br>"+x);
- }
-
- DataTable dt = dbw.ExecuteDataTable("select * from xp_users");
- if (dt != null && dt.Rows.Count > 0)
- {
- this.Context.Response.Write("<br>用户数:"+dt.Rows.Count);
- }
- if (dt != null)
- {
- dt.Dispose();
- dt = null;
- }
- dbw.Dispose();
- dbw = null;