Asp.Net Core 连接MySQL

首先新建一个项目 Asp.NetCoreConnectorMySQL

这里写图片描述

通过简单的修改运行如下

这里写图片描述

接下来安装NuGet安装MySQL的库

这里写图片描述

查看MySQL里面自带的数据库

这里写图片描述

我们来修改json文件(appsettings.json)建立MySQL的连接串

这里写图片描述

新建一个类(这里我的类名是Lexan,你的不一定是Lexan)

        private WorldContext worldcontext { get; set; }
        public string LexanCode { get; set; }
        public string LexanName { get; set; }
        public string LexanContinent { get; set; }
        public string LexanRegion { get; set; }

这里写图片描述

在新建一个操作数据库的类(WorldContext)

        public string ConnectionString { get; set; }

        public WorldContext(string connectionString)
        {
            this.ConnectionString = connectionString;
        }
        private MySqlConnection GetConnection()
        {
            return new MySqlConnection(ConnectionString);
        }
        public List<Country> GetAllCountry()
        {
            List<Country> list = new List<Country>();
            //连接数据库
            using (MySqlConnection msconnection=GetConnection())
            {
                msconnection.Open();
                //查找数据库里面的表
                MySqlCommand mscommand = new MySqlCommand("select * from country",msconnection);
                using (MySqlDataReader reader=mscommand.ExecuteReader())
                {
                    //读取数据
                    while (reader.Read())
                    {
                        list.Add(new Country()
                        {
                            Code = reader.GetString("Code"),
                            Name=reader.GetString("Name"),
                            Continent=reader.GetString("Continent"),
                            Region=reader.GetString("Region")
                        });
                    }
                }
            }
            return list;
        }

这里写图片描述

再修改Startup.cs文件的ConfigureServices方法

 services.Add(new ServiceDescriptor(typeof(WorldContext),new WorldContext(Configuration.GetConnectionString("DefaultConnection"))));

这里写图片描述

新建一个控制器类

WorldContext context = HttpContext.RequestServices.GetService(typeof(Asp.NetCoreConnectorMySQL.Model.WorldContext)) as WorldContext;
            return View(context.GetAllCountrys());

这里写图片描述

添加一个MVC视图页

这里写图片描述

@model IEnumerable<AspNetCoreConnectionMySQL.Model.Country>
@{ 
    ViewBag.Title = "Lexan";
}
<h1>国家</h1>
<table class="table">
    <tr>
        <th>国家代码</th>
        <th>国家名</th>
        <th>陆地</th>
        <th>区域</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@Html.DisplayFor(modelitem=>item.Code)</td>
            <td>@Html.DisplayFor(modelitem=>item.Name)</td>
            <td>@Html.DisplayFor(modelitem=>item.Continent)</td>
            <td>@Html.DisplayFor(modelitem=>item.Region)</td>
        </tr>
    }
</table>

再修改一下项目的属性,然后运行即可

这里写图片描述

这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章