无法使用MySQLConnection连接到MySQL数据库

时间:2014-06-25 16:01:48

标签: c# mysql

我正在使用MySqlConnection类连接到本地MySQL数据库:

SourceHost = ConfigurationManager.AppSettings["sourceHost"];
SourceDatabase = ConfigurationManager.AppSettings["sourceDatabase"];
SourceUsername = ConfigurationManager.AppSettings["sourceUsername"];
SourcePassword = ConfigurationManager.AppSettings["sourcePassword"];

SourceString = String.Format("Server={0};Database={1};UID={2};Password={3};", SourceHost, SourceDatabase, SourceUsername, SourcePassword);
var sqlSourceConnection = new MySqlConnection(SourceString);

sqlSourceConnection.Open();

这些是App.config文件中的值

<add key="sourceHost" value="myHost" />
<add key="sourceDatabase" value="myDB" />
<add key="sourceUsername" value="myUSer" />
<add key="sourcePassword" value="myPSW" />
<add key="sourceDbType" value="mysql" />

我得到的错误是:用户myUser@myHost.myDomain使用密码拒绝访问:是,但是通过使用myUser和myPSW凭据我可以从命令提示符登录。

怎么了?

编辑:当我将sourceHost更改为

时,它有效
<add key="sourceHost" value="localhost" />

3 个答案:

答案 0 :(得分:3)

用户myUser仅授权来自localhost。
您需要为您的主机名授权myUser。

GRANT ALL PRIVILEGES ON *.* to 'myUser'@'%' WITH GRANT OPTION;

GRANT ON *.* TO 'myUser'@'myHost.myDomain' IDENTIFIED BY 'password' ;

或者您也可以

GRANT ON *.* TO 'myUser'@'%.myDomain' IDENTIFIED BY 'password' ;

答案 1 :(得分:0)

标准

Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

指定TCP端口

Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

端口3306是默认的MySql端口。如果使用Unix套接字,则忽略该值。

答案 2 :(得分:0)

当您尝试SHOW GRANTS时,您会看到如下所示的行:

mysql> SHOW GRANTS;
+-----------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'myUSer'@'localhost' WITH GRANT OPTION |
+-----------------------------------------------------------------------+

请注意localhost,因此连接时会发生这种情况:

  • 当您尝试连接到localhost时,系统会自动使用127.0.0.1作为连接源地址。
  • 但是当您连接到10.0.0.1时,它会使用10.0.0.1作为您的来源地址。

试试ping with -S

C:\>ping localhost -S 127.0.0.1

Pinging localhost [127.0.0.1] from 127.0.0.1 with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128

C:\>ping localhost -S 10.0.0.1

Pinging localhost [127.0.0.1] from 10.0.0.1 with 32 bytes of data:
PING: transmit failed. General failure.

C:\>ping 10.0.0.1 -S 10.0.0.1

Pinging 10.0.0.1 from 10.0.0.1 with 32 bytes of data:
Reply from 10.0.0.1: bytes=32 time<1ms TTL=128

C:\>ping 10.0.0.1 -S 127.0.0.1

Pinging 10.0.0.1 from 127.0.0.1 with 32 bytes of data:
PING: transmit failed. General failure.

因此,它适用于localhost,因为localhost允许的源主机,而your_host不是10.0.0.1,因为10.0.0.1是不是允许的主人。

只需将用户的权限授予%并且它应该有效(可能您必须更改防火墙设置),或允许来自外部的所有连接(使用{{1}}作为主机)。< / p>