While I am trying to close the JDBC it is throwing NullPointerException
.
public void getDBConnection() throws SQLException {
Driver driver = new Driver();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root123");
}
public void closeDB() throws SQLException {
conn.close();
}
you have to assure before close connection that conn
instance initialized or not. so once need to call getDBConnection
method, because conn
object initialize in it. then you can call closeDB
. Add check like if(conn != null)
to be safe side.
Use try-with-resource statement of Java 7. It is AutoCloseable
by default. It is safe and easy. For example,
try(Connection con=DriverManager.getConnection(..)){
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.