創(chuàng)建ASP.NET Core MVC應(yīng)用程序(2)-利用MySQL Connector NET連接到MySQL
用慣.NET的研發(fā)人員都習(xí)慣性地使用SQLServer作為數(shù)據(jù)庫(kù)。然而.NET Core都玩開(kāi)源了,那么本文我就采用MySQL數(shù)據(jù)庫(kù)。
安裝MySQL
首先從官網(wǎng)下載MySQL安裝包。在Mac下會(huì)安裝到/usr/local/mysql/bin/mysql
文件目錄下。
Mac下安裝完成之后可以在系統(tǒng)偏好設(shè)置查看到MySQL:
然后將MySQL路徑加入到環(huán)境變量之中:
- 打開(kāi)終端,輸入如下命令,進(jìn)入到~文件夾:
cd ~
- 輸入?如下命令,以創(chuàng)建一個(gè)文件:
touch .bash_profile
touch命令有兩個(gè)功能:
- 用于把已存在文件的時(shí)間標(biāo)簽更新為系統(tǒng)當(dāng)前的時(shí)間(默認(rèn)方式),它們的數(shù)據(jù)將原封不動(dòng)地保留下來(lái)。
- 二是用來(lái)創(chuàng)建新的空文件。
- 輸入?如下命令,以打開(kāi)該文件:
open -e .bash_profile
open命令是Mac OS專(zhuān)用的命令行,用于打開(kāi)文件、目錄或執(zhí)行程序。就等同于在命令行模式下,重復(fù)圖形界面“雙擊”的動(dòng)作。
可以使用-a選項(xiàng)要求自行選擇打開(kāi)的程序,或使用-e強(qiáng)制在TextEdit中編輯此文件。
在TextEdit中打開(kāi)該文件,如果沒(méi)有配置過(guò)環(huán)境變量,則會(huì)是一個(gè)空白文檔。在里面輸入:“export PATH=${PATH}:/usr/local/mysql/bin”即可。
配置連接字符串
打開(kāi)appsettings.json,添加MySQL的連接字符串信息,此處使用MySQL的示例數(shù)據(jù)庫(kù)sakila。類(lèi)似于SQLServer的示例數(shù)據(jù)庫(kù)AdventureWorks
、Northwind
。
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"MyConnection": "server=localhost;userid=root;pwd=(<你的密碼>);port=3306;database=sakila;sslmode=none;"
}
}
添加MySQL相關(guān)依賴(lài)項(xiàng)
首先在project.json文件中添加EntityFrameworkCore依賴(lài)項(xiàng),添加MySQL Connector for .NET Core引用;并在buildOptions
section里面指定將appsettings.json復(fù)制到output里面。
最終的文件結(jié)果類(lèi)似于這樣:
{
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.1",
"type": "platform"
},
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.Razor.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
},
"Microsoft.AspNetCore.Routing": "1.0.1",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
"Microsoft.Extensions.Logging": "1.0.0",
"Microsoft.Extensions.Logging.Console": "1.0.0",
"Microsoft.Extensions.Logging.Debug": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
"Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
"MySql.Data.Core": "7.0.4-ir-191",
"MySql.Data.EntityFrameworkCore": "7.0.4-ir-191"
},
"tools": {
"BundlerMinifier.Core": "2.0.238",
"Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true,
"copyToOutput": {
"include": "appsettings.json"
}
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"publishOptions": {
"include": [
"wwwroot",
"**/*.cshtml",
"appsettings.json",
"web.config"
]
},
"scripts": {
"precompile": ["dotnet bundle"],
"prepublish": ["bower install"],
"postpublish": ["dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"]
},
"tooling": {
"defaultNamespace": "MyFirstApp"
}
}
最后運(yùn)行dotnet restore
命令,該命令將會(huì)下載所有需要的依賴(lài)項(xiàng)。
添加MySQL示例數(shù)據(jù)庫(kù)Sakila
這里我們將使用MySQL示例數(shù)據(jù)庫(kù)sakila作為演示。
- 將下載的壓縮包解壓到臨時(shí)路徑,通過(guò)mysql命令行連接到MySQL Server:
mysql -u root -p
- 通過(guò)如下命令執(zhí)行sakila-schema.sql來(lái)創(chuàng)建數(shù)據(jù)庫(kù)結(jié)構(gòu):
SOURCE /Users/CharlieChu/Desktop/sakila-db/sakila-schema.sql;
- 通過(guò)如下命令執(zhí)行sakila-data.sql來(lái)填充上個(gè)命令創(chuàng)建的數(shù)據(jù)庫(kù)結(jié)構(gòu):
SOURCE /Users/CharlieChu/Desktop/sakila-db/sakila-data.sql;
- 利用如下命令確認(rèn)已經(jīng)安裝成功:
USE sakila;
SHOW TABLES;
如下是執(zhí)行的具體效果:
獲取MySQL數(shù)據(jù)庫(kù)數(shù)據(jù)
從Sakila數(shù)據(jù)庫(kù)Category表獲取信息:
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var configuration = builder.Build();
string connectionString = configuration.GetConnectionString("MyConnection");
MySqlConnection connection = new MySqlConnection
{
ConnectionString = connectionString
};
connection.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM sakila.customer;", connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
System.Console.WriteLine("Customer Id\t\tFirst Name\t\tLast Name\t\tEmail");
while (reader.Read())
{
string row = $"{reader["customer_id"]}\t\t{reader["first_name"]}\t\t{reader["last_name"]}\t\t{reader["email"]}";
System.Console.WriteLine(row);
}
}
connection.Close();
System.Console.ReadKey();
}
運(yùn)行dotnet run
即可查看具體的數(shù)據(jù)。