我在连接到本地MySQL数据库时遇到问题。
我确保服务器正在运行,并且可以使用连接字符串中的用户名和密码连接到服务器,并使用终端创建数据库。
我在Mac和MySQL 8.0.16上使用Visual Studio社区。
示例: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ReadSQL
{
class Program
{
static void Main(string[] args)
{
DataAccess dataAccess = new DataAccess();
dataAccess.GetTask();
}
}
}
DataAccess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
namespace ReadSQL
{
public class DataAccess
{
public List<Task> GetTask()
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("workloadDB")))
{
var output = connection.Query<Task>($"select * from task where id=1").ToList(); //exception thrown here
Console.WriteLine(output);
}
}
}
}
Helper.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadSQL
{
public static class Helper
{
public static string CnnVal(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
}
Task.cs
using System;
namespace ReadSQL
{
public class Task
{
int id { get; set; }
string name { get; set; }
}
}
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="workloadDB" connectionString="Server=localhost;Database=workload;Uid=root;Pwd=adminPasswort;" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
我希望变量输出包含表的第一行,但是却收到错误消息:
System.Data.SqlClient.SqlException 发生与网络相关或特定于实例的错误 建立与sql server的连接。找不到服务器或 无法访问。验证实例名称正确,并且 SQL Server配置为允许远程连接。
我不知道为什么无法建立连接,因为MySQL Server肯定正在运行,并且连接字符串应该正确(也尝试过:trusted_connection = true;)。 预先感谢!
答案 0 :(得分:1)
您不能使用SqlConnection
类连接到MySQL。而是从NuGet安装MySqlConnector,然后使用:
using (IDbConnection connection = new MySqlConnection(Helper.CnnVal("workloadDB")))
{
var output = connection.Query<Task>($"select * from task where id=1").ToList();
}
您的连接字符串看起来应该与MySqlConnection
兼容,但是如果您使用任何其他选项,则应对照the list of valid connection options仔细检查它们。