Troubleshooting MySQL Connection Failure in Java
Problem: Connecting to a MySQL database from a Java program results in a NullPointerException error when invoking DriverManager.getConnection().
Code Example:
import java.sql.*; public class Squirrel { public static void main(String[] args) { String user; String password; Connection connection; Statement statement; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306", user, password); statement = connection.createStatement(); // Other code } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
Error Message:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. ... Caused by: java.lang.NullPointerException at com.mysql.jdbc.ConnectionImpl.getServerCharset(ConnectionImpl.java:2997)
Solution:
The NullPointerException error indicates an issue with the MySQL driver initialization. The most common cause is using an outdated version of the MySQL JDBC driver.
Update the MySQL JDBC Driver:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency>
Additional Fix (for MySQL 8.0.1 ):
If the issue persists, it may be related to changes introduced in MySQL 8.0.1. To resolve this:
jdbc:mysql://localhost:3306/?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
The above is the detailed content of Why am I getting a NullPointerException when connecting to a MySQL database from Java?. For more information, please follow other related articles on the PHP Chinese website!