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>

再修改一下項目的屬性,然後運行即可

這裏寫圖片描述

這裏寫圖片描述

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