I have written the following java code to connect the Oracle Express Edition database.....I have read a lot about closing the connection, statement and result but there are some questions about this issue...
1- I usually test my code several time so If I Don not close the connection and etc. will I face with any problem?!!(because the connection is made on the same variable or object in my code!!!!)
2-how can I understand how many connections exist now?(after testing the code for several time)
3- Should I place CLOSE methods in finally block with a new TRY CATCH block or add THROWS SQLException after main method?!!!! what is the difference between these to implementation?!!!
package mainAssignment;
import java.sql.*;
import java.text.MessageFormat;
import java.math.*;
import java.util.*;
//import java.text.MessageFormat;
public class Conn {
/**
* @param args
*/
public static void main(String[] args)throws SQLException{
// TODO Auto-generated method stub
String jdbcURL = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String user = "hr";
String passwd = "hr";
Scanner input = new Scanner(System.in);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(jdbcURL, user, passwd);
System.out.println("ok");
System.out.println("Please enter the desired employee ID: ");
Object[] arg={new String(input.nextLine())};
String query = MessageFormat.format(
"select * from EMPLOYEES where employee_id={0}", arg);
//System.out.println(query);
stmt = conn.createStatement();
stmt.executeQuery(query);
rs = stmt.getResultSet();
while (rs.next()) {
BigDecimal empid = rs.getBigDecimal(1);
String firstname = rs.getString("FIRST_NAME");
System.out.println("employee ID " + empid
+ " first name is " + firstname);
}
} catch (SQLException e) {
e.printStackTrace();
// TODO
} catch (ClassNotFoundException e) {
// TODO
e.printStackTrace();
} finally {
conn.close();
rs.close();
if (conn.isClosed())
System.out.println("no connection any more");
else
System.out.println("connection exists");
}
}
}