2013-04-22 198 views
0

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

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 
+1

你试图连接到SQL服务器或MySQL? – wayne 2013-04-22 05:17:18

+0

我正在尝试连接到mysql – fotg 2013-04-22 05:20:13

+1

'SqlConnection'仅*用于连接到Microsoft SQL Server。你不能用它连接到MySQL。 – 2013-04-22 05:20:30

回答

2

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

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

可以找到介绍here

0

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

+0

不,这不起作用要么 – fotg 2013-04-22 05:20:48

+0

你为什么认为这有所作为? – 2013-04-22 05:20:54

+0

当我编写我的php脚本连接到我的数据库时,当我使用本地主机时它不起作用,但是当我输入127.0.0.1时它不起作用。不知道为什么,但那就是发生了什么。 – 2013-04-22 05:22:30

0
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); 
}