以下代码运行时没有任何错误并输出MySQL版本:
public class ConnectionMain {
public static void main(String[] args) {
MySqlConnection mySqlConnection = new MySqlConnection();
mySqlConnection.printVersion();
}
}
但是当我尝试在客户端或服务器代码(同一个项目)中的任何位置运行printVersion()
函数时,我得到java.lang.ClassNotFoundException
的着名com.mysql.jdbc.Driver
。可能导致此问题的原因是什么?当我运行项目时,mysql-connector.jar
是否无法正常构建?该文件已经是IntelliJ依赖项。
import java.sql.*;
import java.util.Properties;
public class MySqlConnection {
private final static Logger.Log LOG = Logger.newLog(MySqlConnection.class);
private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/message_db?useSSL=false";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
private Properties properties;
private Statement statement;
private ResultSet rs;
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
}
return properties;
}
private Connection connect() {
Connection connection;
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
if (connection != null) {
return connection;
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ERROR: Exception in MySqlConnection.connect. Check log for details.");
LOG.error(e, "Exception in MySqlConnection.connect");
}
return null;
}
private void close() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (statement != null) {
statement.close();
statement = null;
}
} catch (SQLException e) {
System.out.println("ERROR: Exception in MySqlConnection.close. Check log for details.");
LOG.error(e, "Exception in MySqlConnection.close");
}
}
public void printVersion() {
Connection connection = connect();
try {
statement = connection.createStatement();
rs = statement.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
LOG.info(rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
if (connection != null) {
connection.close();
}
}
}
}