我已经编写了以下java代码来连接Oracle Express Edition数据库......我已经阅读了很多关于关闭连接、语句和结果的信息,但是关于这个问题有一些问题......
1-我通常会多次测试我的代码,所以如果我不关闭连接等,我会遇到任何问题吗?!!(因为连接是在我的代码中的同一个变量或对象上建立的!!!!)
2-我怎么知道现在有多少个连接?(经过多次测试代码)
3-我应该将 CLOSE 方法放在 finally 块中并使用新的 TRY CATCH 块还是在 main 方法之后添加 THROWS SQLException?!!!!这些与实施有什么区别?!!!
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");
}
}
}