Project

Profile

Help

Bug #6286 » Main.java

Johan Gheys, 2023-12-14 16:03

 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
public static void main(String[] args) throws SQLException {
String dbString = "jdbc:oracle:thin:@//localhost:1521/XEPDBUPM";
String userString = "A171";
String pwdString = "A171";

Connection connection = DriverManager.getConnection(dbString, userString, pwdString);

PreparedStatement preparedStatement = connection.prepareStatement("select id from application_date");
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
System.out.println(id);
}
preparedStatement.close();

// Direct close
// connection.close();

// or close via reflection
try {
close(connection);
} catch (Exception e) {
System.out.println(e);
}
}

private static void close(Connection connection) throws InvocationTargetException, IllegalAccessException {
Class<?> connectionClass = Connection.class;
Method closeMethod = null;
while (closeMethod == null) {
try {
closeMethod = connectionClass.getMethod("close");
System.out.println("found close() method on class " + connectionClass.getName());
} catch (Exception e) {
connectionClass = connectionClass.getSuperclass();
}
}
if (closeMethod != null) {
// No need to call : closeMethod.setAccessible(true);
closeMethod.invoke(connection);
}
}
}
(1-1/2)