【问题标题】:Can't connect to mysql 5.6 database无法连接到 mysql 5.6 数据库
【发布时间】:2013-04-14 22:15:19
【问题描述】:

我一直在尝试连接到 MySQL 数据库,但收到异常 0x80131904:找不到服务器。我知道服务器正在运行,我可以通过命令行查询它。我还确保未启用跳过网络。我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Data.SqlClient;

class Program
    {
    static void Main(string[] args)
        {

        Console.WriteLine("Connecting to database...");

        SqlConnection sqlserver = new SqlConnection("user id=<removed>;" +
                                  "password=<removed>;server=localhost;" +
                                  "Trusted_Connection=yes;" +
                                  "database=ircbot; " +
                                  "connection timeout=5");

        try
            {
            sqlserver.Open();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Connected");
            Console.ResetColor();
            }
        catch (Exception e)
            {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(e.ToString());
            Console.ResetColor();
            }

        Console.ReadLine();
        }    //end main


    }  //end class Program

【问题讨论】:

  • 你是要连接sql server还是mysql?
  • 我正在尝试连接到 mysql
  • SqlConnection 用于连接到 Microsoft SQL Server。你不能用它来连接 MySQL。
  • 要从 C# 连接到 MySQL,请参阅 here

标签: c# mysql localhost database-connection


【解决方案1】:

SqlConnection用于连接 Microsoft SQL Server,您不能使用它连接任何其他 DBMS,例如 MySQL。

为了能够从 C# 连接到 MySQL,您需要 MySQL Connector/Net。它带有一个MySqlConnection 类和相应的数据读取器和参数类。

介绍可以在here找到。

【讨论】:

    【解决方案2】:
    MySql.Data.MySqlClient.MySqlConnection conn;
    string myConnectionString;
    
    myConnectionString = "server=127.0.0.1;uid=root;" +
    "pwd=12345;database=test;";
    
    try
    {
    conn = new MySql.Data.MySqlClient.MySqlConnection();
    conn.ConnectionString = myConnectionString;
    conn.Open();
    }
    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
    

    【讨论】:

      【解决方案3】:

      尝试使用 127.0.0.1 而不是 'localhost' 作为您的服务器。

      【讨论】:

      • 您认为这有何不同?
      • 当我编写我的 php 脚本连接到我的数据库时,当我使用 localhost 时它不起作用,但当我输入 127.0.0.1 时它会起作用。不知道为什么,但就是这样。
      • @MichaelDeluca:感谢您的澄清。只是想确保您的答案实际上是基于某些东西:)
      猜你喜欢
      • 2018-08-22
      • 2016-12-03
      • 2014-01-25
      • 1970-01-01
      • 2018-02-06
      • 2016-12-13
      • 2013-03-05
      • 2012-12-08
      相关资源
      最近更新 更多