.net连接mysql数据_.net连接MySQL数据库

1、通过Visual Stdio新建.net项目

(1)新建项目

6de9dc8f60e3f0ba9293f38897357e1e.png

(2)选择项目配置

57cac58a57a19a46514fa9600b212741.png

(3)项目结构

bdc957263450c7486d9ffa605e8e3000.png

(4)新建一个Controller,名称要取HomeController

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespaceWebApplication1.Controllers

{public classHomeController : Controller

{//GET: Home

publicString Index()

{return "Hello world";

}

}

}

测试:

9a6be522c768da6ed5ca18df33cbfbfa.png

2、创建ODBC数据源

(1)下载ODBC数据源

f364a2cc1690350d4b59275eefb33656.png

(2)配置ODBC数据源

46b35581c810a85ba246acbb6a5bc838.png

添加相关的信息后点击测试:

95eb8821a42289b70d64cdf37b244c75.png

3、.net连接MySQL数据库

方式一:

(1)添加引用

b95945730792178d4bb185a9726b4706.png

(2)添加一个Web窗体

2fe62d1ef1cd95684f92dd1874225627.png

(3)设计页面

选择工具:

30b279736068f338a4e1cc7230ceed0c.png

(4)连接数据源(该数据源是前面已经配置了的数据源)

a3649bd3ad8c865fa294d52b084513e4.png

双击SQL数据库

(5)测试

9b9f8cce22e36eb5a80605ee70963eaa.png

(6)运行生成的页面即可

c8693bc859d019cae9f87806bea223cb.png

(7)生成的代码如下

方式二:

在程序中进行书写获取数据库连接相关的代码,获取到数据库连接并操作数据库

(1)引用MySql.Data

(2)书写代码获取数据库连接,操作数据库

namespaceWebApplication1.Controllers

{public classHomeController : Controller

{publicMySqlDataReader Index()

{

String constr= "server=127.0.0.1;user=root;password=root; database=student;";

MySqlConnection mycn= newMySqlConnection(constr);try{

mycn.Open();

Console.WriteLine("已经建立连接");

}catch(MySqlException ex)

{

Console.WriteLine(ex.Message);

}

MySqlCommand mycm= new MySqlCommand("select * from student", mycn);

MySqlDataReader dr=mycm.ExecuteReader();while(dr.Read())

{if(dr.HasRows)

{

Response.Write(dr.GetString("sname") + "
");

}

}

mycn.Close();returndr;

}

}

}

(3)测试

418814fc4003abfff2111ab7c2cc8f1b.png

方式三:

(1)书写连接数据库的配置文件

(2)书写获取数据库连接的工具类

namespaceWebApplication1.utils

{public classConnectionUtils

{public staticMySqlConnection CreateConn()

{string _conn = WebConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

MySqlConnection conn= newMySqlConnection(_conn);returnconn;

}

}

}

(3)书写测试类

namespaceWebApplication1.Controllers

{public classHomeController : Controller

{publicMySqlDataReader Index()

{

MySqlConnection mycn=ConnectionUtils.CreateConn();try{

mycn.Open();

Console.WriteLine("已经建立连接");

}catch(MySqlException ex)

{

Console.WriteLine(ex.Message);

}

MySqlCommand mycm= new MySqlCommand("select * from student", mycn);

MySqlDataReader dr=mycm.ExecuteReader();while(dr.Read())

{if(dr.HasRows)

{

Response.Write(dr.GetString("sname") + "
");

}

}

mycn.Close();returndr;

}

}

}

(4)测试

02f4c06f1199eb8a3ac15bea24bcef55.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值