mysql asp.net core_MySQL数据库之AspNetCore使用MySQL
本文主要向大家介绍了MySQL数据库之AspNetCore使用MySQL ,通过具体的内容向大家展现,希望对大家学习MySQL数据库有所帮助。既然NetCore开源,那么也使用开源的MySQL的数据库呢?当然NetCore不止单单配MSSQL数据库而已。今天我来讲解NetCore怎么使用MySQL进行开发。首先新建一个NetCore项目技术分享技术分享然后写两个类放在Model里面publicc.
本文主要向大家介绍了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 GetLexan()
{
List list = new List();
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
@{
ViewBag.Title = "Lexan";
}
Lexan
| 名字 | 性别 | 年龄 |
|---|
@foreach (var item in Model)
{
@Html.DisplayFor(modelitem => item.Name)@Html.DisplayFor(modelitem => item.Sex)@Html.DisplayFor(modelitem => item.Age)}
然后修改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数据库频道!
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)