既然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;
全部工作完成了,我们来运行看看效果