建立ASP.NET Core MVC應用程序(2)-利用MySQL Connector NET鏈接到MySQL

建立ASP.NET Core MVC應用程序(2)-利用MySQL Connector NET鏈接到MySQL

用慣.NET的研發人員都習慣性地使用SQLServer做爲數據庫。然而.NET Core都玩開源了,那麼本文我就採用MySQL數據庫。html

安裝MySQL

首先從官網下載MySQL安裝包。在Mac下會安裝到/usr/local/mysql/bin/mysql文件目錄下。mysql

Mac下安裝完成以後能夠在系統偏好設置查看到MySQL:git


而後將MySQL路徑加入到環境變量之中:github

  • 打開終端,輸入以下命令,進入到~文件夾:
cd ~
  • 輸入以下命令,以建立一個文件:
touch .bash_profile

touch命令有兩個功能:1)用於把已存在文件的時間標籤更新爲系統當前的時間(默認方式),它們的數據將原封不動地保留下來。2)二是用來建立新的空文件。web

  • 輸入以下命令,以打開該文件:
open -e .bash_profile

open命令是Mac OS專用的命令行,用於打開文件、目錄或執行程序。就等同於在命令行模式下,重複圖形界面「雙擊」的動做。
能夠使用-a選項要求自行選擇打開的程序,或使用-e強制在TextEdit中編輯此文件。sql

在TextEdit中打開該文件,若是沒有配置過環境變量,則會是一個空白文檔。在裏面輸入:「export PATH=${PATH}:/usr/local/mysql/bin」便可。數據庫

這裏順便貼一張最近與MySQL之父Michael "Monty" Widenius大神的合影(其實MySQL的"My"是命名來自於Monty的女兒My)。
膜拜一下大神,沾一點編程的靈氣。編程

配置鏈接字符串

打開appsettings.json,添加MySQL的鏈接字符串信息,此處使用MySQL的示例數據庫sakila。相似於SQLServer的示例數據庫AdventureWorksNorthwindjson

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "ConnectionStrings": {
        "MyConnection": "server=localhost;userid=root;pwd=(<你的密碼>);port=3306;database=sakila;sslmode=none;"
    }
}

添加MySQL相關依賴項

首先在project.json文件中添加EntityFrameworkCore依賴項,添加MySQL Connector for .NET Core引用;並在buildOptionssection裏面指定將appsettings.json複製到output裏面。bash



最終的文件結果相似於這樣:

{
    "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"
    }
}

最後運行dotnet restore命令,該命令將會下載全部須要的依賴項。

添加MySQL示例數據庫Sakila

這裏咱們將使用MySQL示例數據庫sakila做爲演示。

  • 將下載的壓縮包解壓到臨時路徑,經過mysql命令行鏈接到MySQL Server:
mysql -u root -p
  • 經過以下命令執行sakila-schema.sql來建立數據庫結構:
SOURCE /Users/CharlieChu/Desktop/sakila-db/sakila-schema.sql;
  • 經過以下命令執行sakila-data.sql來填充上個命令建立的數據庫結構:
SOURCE /Users/CharlieChu/Desktop/sakila-db/sakila-data.sql;
  • 利用以下命令確認已經安裝成功:
USE sakila;
SHOW TABLES;

以下是執行的具體效果:


獲取MySQL數據庫數據

從Sakila數據庫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();
}

運行dotnet run便可查看具體的數據。

參考文檔

我的博客

個人我的博客

相關文章
相關標籤/搜索