创建ASP.NET Core MVC应用程序(2)-利用MySQL Connector NET连接到MySQL

    xiaoxiao2021-11-30  40

    创建ASP.NET Core MVC应用程序(2)-利用MySQL Connector NET连接到MySQL

    用惯.NET的研发人员都习惯性地使用SQLServer作为数据库。然而.NET Core都玩开源了,那么本文我就采用MySQL数据库。

    安装MySQL

    首先从官网下载MySQL安装包。在Mac下会安装到/usr/local/mysql/bin/mysql文件目录下。

    Mac下安装完成之后可以在系统偏好设置查看到MySQL:

    然后将MySQL路径加入到环境变量之中:

    打开终端,输入如下命令,进入到~文件夹: cd ~ 输入如下命令,以创建一个文件: touch .bash_profile

    touch命令有两个功能: * 用于把已存在文件的时间标签更新为系统当前的时间(默认方式),它们的数据将原封不动地保留下来。 * 二是用来创建新的空文件。

    输入如下命令,以打开该文件: open -e .bash_profile

    open命令是Mac OS专用的命令行,用于打开文件、目录或执行程序。就等同于在命令行模式下,重复图形界面“双击”的动作。 可以使用-a选项要求自行选择打开的程序,或使用-e强制在TextEdit中编辑此文件。

    在TextEdit中打开该文件,如果没有配置过环境变量,则会是一个空白文档。在里面输入:“export PATH=${PATH}:/usr/local/mysql/bin”即可。

    配置连接字符串

    打开appsettings.json,添加MySQL的连接字符串信息,此处使用MySQL的示例数据库sakila。类似于SQLServer的示例数据库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相关依赖项

    首先在project.json文件中添加EntityFrameworkCore依赖项,添加MySQL Connector for .NET Core引用;并在buildOptionssection里面指定将appsettings.json复制到output里面。

    最终的文件结果类似于这样:

    { "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即可查看具体的数据。

    参考文档

    MySql Connector NET for .NET Core 1.0

    个人博客

    我的个人博客

    转载请注明原文地址: https://ju.6miu.com/read-679048.html

    最新回复(0)