AspNetCore使用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;

全部工作完成了,我们来运行看看效果

最后博主在这里说一下,凡是本博主的博文,麻烦添加原文地址,谢谢!所有博客文章都来自Lexan的博客,你也可以关注博主的博文地址http://www.cnblogs.com/R00R/

原文地址:https://www.cnblogs.com/R00R/p/7145123.html