【问题标题】:JDBC connection not recognizing an existing DatabaseJDBC 连接无法识别现有数据库
【发布时间】:2026-01-06 09:40:01
【问题描述】:

我从浏览器创建了一个名为“test”的数据库,现在尝试使用 JDBC 驱动程序和语法从 java 代码访问它:

Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "pw");
            st = con.createStatement();

我收到错误:

Error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'test' 

我搜索了它,我得到了可能的解决方案“创建名为'test'的数据库”,但那里已经存在。可能是什么原因以及如何处理?

编辑:

我的 conf 文件有一个类似的 sn-p:

# The following options will be passed to all MySQL clients
[client]
#password   = your_password
port        = 3306
socket      = /tmp/mysql.sock

# Here follows entries for some specific programs

# The MySQL server
[wampmysqld]
port        = 3306
socket      = /tmp/mysql.sock

显示端口确实是3306

【问题讨论】:

  • 使用终端检查数据库是否创建。
  • 我用浏览器检查了一下,它就在那里。
  • 你用来连接的用户是否真的有访问数据库test的权限? (我知道您与root 联系,但检查一下也无妨)。
  • 也在浏览器中,我使用用户名:“root”和密码“pw”登录。不然怎么查?

标签: java mysql jdbc


【解决方案1】:

您似乎忘记了您的端口号。默认是 3306。所以你可以把它改成

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "pw"); 看看这是否有效。

希望对你有帮助。

【讨论】:

  • 我尝试了这个并编辑了问题,但这不起作用。
  • 您不需要指定默认端口。如果没有明确指定端口,驱动程序将采用默认值