使用 JDBC 连接到 MySQL 数据库时出现问题
以下是我尝试连接的方式:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
throw new DbConnectionException();
}
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
throw new DbConnectionException();
}
我 100% 确定 url、用户名、密码字符串是正确的。我已经使用外部工具(MySQL 查询浏览器)成功连接。 这是我收到的错误:
com.mysql.jdbc.CommunicationsException: 由于以下原因导致通讯链路故障 底层异常:
** 开始嵌套异常 **
java.net.SocketException 消息: java.net.ConnectException:连接 拒绝
...
Here's how I'm trying to connect:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
throw new DbConnectionException();
}
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
throw new DbConnectionException();
}
I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:
com.mysql.jdbc.CommunicationsException:
Communications link failure due to
underlying exception:** BEGIN NESTED EXCEPTION **
java.net.SocketException MESSAGE:
java.net.ConnectException: Connection
refused...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可能是
url
问题。如果您的代码指向 MySQLlocalhost
,请尝试将 URL 上的localhost
更改为127.0.0.1
。例如:
看看
这是否有效。
Possibly a
url
issue. If your code is pointing to MySQLlocalhost
, try changinglocalhost
to127.0.0.1
on your url.E.g.:
to
And see if this works.
您是否在运行代码的同一台机器上运行 mysql 浏览器?我得到的是 mysql 中的权限可以是特定于主机的,并且根据您如何设置它们,您可能无法从运行代码的计算机进行连接。
另外,您可能需要再次仔细检查 url、名称、密码,也许使用日志语句或调试器来确保没有拼写错误、尾随空格等...
did you run the mysql browser from the same machine where the code is running? What I am getting at is the permissions in mysql can be host-specific, and depending on how you set them up you might not be able to connect from the machine where the code is running.
Also, you might want to double check the url, name, pword again, perhaps with log statements or a debugger to make sure there are no typos, trailing whitespaces, etc...
仔细检查您的网址格式。它应该以“jdbc:mysql:”开头。确保您也使用最新版本的驱动程序。
Double check the format of your url. It should start with "jdbc:mysql:". Make sure you are using a current version for the driver as well.
检查您是否可以从 mysql 管理工具连接到数据库,这将确定您的 mysql 是否正在运行以及端口是否打开。
Check that you can connect to the database from the mysql admin tool, that will drive out whether your mysql is running and that the port is open.
就我而言,问题是我正在使用从模拟器到本地主机的连接。
如果您使用模拟器到本地主机,请不要在连接字符串中使用
localhost
值,而是使用10.0.2.2
:希望这会有所帮助。
In my case the problem was that I was using a connection from emulator to localhost.
If you use emulator to localhost don't use
localhost
value in connection String but use10.0.2.2
instead:Hope this helps.