摘要:本文主要向大家介绍了MySQL数据库之AspNetCore使用MySQL ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。
本文主要向大家介绍了MySQL数据库之AspNetCore使用MySQL ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。
既然NetCore开源,那么也使用开源的MySQL的数据库呢?当然NetCore不止单单配MSSQL数据库而已。今天我来讲解NetCore怎么使用MySQL进行开发。
首先新建一个NetCore项目
技术分享
技术分享
然后写两个类放在Model里面
public class Lexan
{
private LexanContext lexanContext;
public string Name { get; set; }
public int Sex { get; set; }
public int Age { get; set; }
}
技术分享
public class LexanContext
{
public string ConnectionString { get; set; }
public LexanContext(string connectionString)
{
ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<Lexan> GetLexan()
{
List<Lexan> list = new List<Lexan>();
using (MySqlConnection connection=GetConnection())
{
connection.Open();
MySqlCommand command = new MySqlCommand("select * from Lexan",connection);
using (MySqlDataReader reader=command.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Lexan()
{
Name=reader.GetString("Name"),
Sex=reader.GetInt32("Sex"),
Age=reader.GetInt32("Age")
});
}
}
}
return list;
}
}
技术分享
技术分享
然后在NuGet库里安装个插件才能完成连接MySQL
技术分享
技术分享
然后添加一个控制器
技术分享
public IActionResult Index()
{
LexanContext wordcontext = HttpContext.RequestServices.GetService(typeof(AspNetCoreUseMySQL.Model.LexanContext)) as LexanContext;
return View(wordcontext.GetLexan());
//return View();
}
技术分享
然后添加一个MVC 视图
技术分享
然后添加如下代码,你也可以根据自己的情况稍作修改
技术分享
@model IEnumerable<AspNetCoreUseMySQL.Model.Lexan>
@{
ViewBag.Title = "Lexan";
}
<h1>Lexan</h1>
<table class="table">
<tr>
<th>名字</th>
<th>性别</th>
<th>年龄</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelitem => item.Name)</td>
<td>@Html.DisplayFor(modelitem => item.Sex)</td>
<td>@Html.DisplayFor(modelitem => item.Age)</td>
</tr>
}
</table>
然后修改Startup类,添加如下代码
services.Add(new ServiceDescriptor(typeof(LexanContext), new LexanContext(Configuration.GetConnectionString("DefaultConnection"))));
技术分享
然后往appsettings.json里写连接字符串,这里注意一下,每个人的密码都不一样,你也要稍作修改,不然会出现连接出错
技术分享
我们来创建一个数据库,并创建表,然后往里面写一条数据
create database AspNetCoreUseMySql;
use AspNetCoreUseMySql;
show tables;
create table Lexan (name varchar(20),sex char(1),Age char(5));
describe Lexan;
insert into Lexan values(‘Lexan‘,‘0‘,‘22‘);
select * from Lexan;
技术分享
全部工作完成了,我们来运行看看效果
技术分享
技术分享
本文由职坐标整理并发布,希望对同学们学习MySQL有所帮助,更多内容请关注职坐标数据库MySQL数据库频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号