我正在构建gui,这是一个测试数据库是否有连接的按钮。用户必须提供数据库参数,然后必须单击"测试连接"按钮以查看数据库是否连接。但我的问题是,即使我没有给出任何参数,它仍然会为连接返回true。
这是我的代码:
GUI部分,其中输入作为数据库参数发送:
testConnection.addActionListener((ActionEvent e) -> {
DatabaseController dbController = new DatabaseController(databaseUrl.getText(), databaseName.getText(),
databaseUser.getText(), databasePassword.getText());
if(dbController.isDataBaseConnected()) setDatabaseConnectionStatus(connectionSuccessLabel, Color.green);
else setDatabaseConnectionStatus(connectionFailLabel, Color.red);
});
数据库控制器类
package dbConnection;
import java.sql.Connection;
import java.sql.SQLException;
public class DatabaseController{
private Connection connection;
public DatabaseController(String url, String dbName, String user, String password){
defineDatabaseParameters(url, dbName, user, password);
this.connection = new DbConnection()
.connectToDatabase();
}
public boolean isDataBaseConnected(){
System.out.println(connection);
if(connection == null){
return false;
} else {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
}
private void defineDatabaseParameters(String url, String dbName, String user, String password){
DbConnection.DB_URL = "jdbc:mysql://" + url + "/" + dbName.trim();
DbConnection.USER = user.trim();
DbConnection.PASS = password.trim();
}
}
这是我的数据库参数类
package dbConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
// static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// static String DB_URL = "jdbc:mysql://localhost/*********";
//
// static String USER = "root";
// static String PASS = "";
static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String DB_URL;
static String USER ;
static String PASS ;
public Connection connectToDatabase(){
Connection conn = null;
try {
System.out.println("Outpost 1: " + DB_URL);
System.out.println("Outpost 2: " + USER);
System.out.println("Outpost 3: " + PASS);
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
}
现在当我按下"测试连接"按钮并且不提供参数(空字符串),然后它仍然显示连接成功。我还做错了,它仍然是真的吗?这是日志输出: 控制台输出
Outpost 1: jdbc:mysql:///
Outpost 2:
Outpost 3:
com.mysql.jdbc.JDBC4Connection@e29ae34
答案 0 :(得分:0)
好的伙计们。我解决了这个问题。我需要输入所有输入字段,这意味着用户必须添加一些URL(出于某种原因,mySQL也喜欢空url并提供连接)并在DatabaseController类中添加了返回false给我的isDataBaseConnected()方法。见上面的编辑