检查与 MySQL (Java) 的连接
Checking connection to MySQL (Java)
我正在为 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);
}
}
唯一的评论是,如果您知道用户名和密码,我会编辑这些详细信息。
我正在为 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);
}
}
唯一的评论是,如果您知道用户名和密码,我会编辑这些详细信息。