概述
I have problems connecting to a local MySQL database.
I made sure the server is running and i can connect to the server using the user and password from the connection string and create databases with the terminal.
I'm using visual studio community on a mac and MySQL 8.0.16.
Example:
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 GetTask()
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("workloadDB")))
{
var output = connection.Query($"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
I expect the variable output to contain the first row of my table, but instead i get the error message:
System.Data.SqlClient.SqlException
A network-related or instance-specific error occurred while
establishing a connection to sql server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections.
I don't know why i cannot establish the connection, because the MySQL Server is definitely running and the connection string should be correct (also tried: trusted_connection=true;).
Thanks in Advance!
解决方案
You cannot use the SqlConnection class to connect to MySQL. Instead, install MySqlConnector from NuGet, then use:
using (IDbConnection connection = new MySqlConnection(Helper.CnnVal("workloadDB")))
{
var output = connection.Query($"select * from task where id=1").ToList();
}
Your connection string looks like it should be compatible with MySqlConnection, but if you're using any other options you should double-check them against the list of valid connection options.
最后
以上就是俭朴芝麻为你收集整理的连接到本地mysql服务器失败怎么办,连接到本地MySQL服务器时出现问题的全部内容,希望文章能够帮你解决连接到本地mysql服务器失败怎么办,连接到本地MySQL服务器时出现问题所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复