Dev*_*0ps 3 java mysql database-connection jdbc
我正在为 MySQL 创建我的小实用程序,我需要一些帮助。
我如何检查与 MySQL 的连接(通过登录名和密码) ,就像在phpMyAdmin中实现的那样,而无需首先指向某些数据库。因为大多数数据库解决方案都需要这个指向。
提前致谢)
是的。您无需在连接 URL 中指定数据库即可连接到服务器。
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306"; //pointing to no database.
String username = "myusername";
String password = "mypassword";
System.out.println("Connecting to server...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Server connected!");
Statement stmt = null;
ResultSet resultset = null;
try {
stmt = connection.createStatement();
resultset = stmt.executeQuery("SHOW DATABASES;");
if (stmt.execute("SHOW DATABASES;")) {
resultset = stmt.getResultSet();
}
while (resultset.next()) {
System.out.println(resultset.getString("Database"));
}
}
catch (SQLException ex){
// handle any errors
ex.printStackTrace();
}
finally {
// release resources
if (resultset != null) {
try {
resultset.close();
} catch (SQLException sqlEx) { }
resultset = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { }
stmt = null;
}
if (connection != null) {
connection.close();
}
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the server!", e);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8416 次 |
| 最近记录: |