I use the following codes to connect to Oracle’s database:
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
String jdbc_url = "jdbc:oracle:thin:hr/hr@localhost:1521:XE";
String query = "";
try {
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection(jdbc_url);
stmt = conn.createStatement();
query = "select username " + " from users ";
rset = stmt.executeQuery(query);
// my codes
} catch (SQLException sqle) {
System.out.println("result error, " + e.getMessage());
} catch (NumberFormatException nfe) {
} finally {
try {
rset.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println("Error in closing " + e.getMessage());
}
}
Do I have to use this code in every action that I make for every query that I want? Making the connection and terminating it? Everytime?
You don’t have to connect every time. Just make sure you close the resultset and the statement every time. See this answer as example for a good DB wrapper class.
You can make your
Connectiona class variable that is initalized in the constructor. Something like this: