至于连接的使用规范,可以参考任何一个数据库的jdbc使用样例,这里我贴的是mysql的,原文可 以参考http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-examples-connection-drivermanager // assume that conn is an already created JDBC connection Statement stmt = null; ResultSet rs = null;try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT foo FROM bar"); // or alternatively, if you don't know ahead of time that // the query will be a SELECT... if (stmt.execute("SELECT foo FROM bar")) { rs = stmt.getResultSet(); } // Now do something with the ResultSet .... } finally { // it is a good idea to release // resources in a finally{} block // in reverse-order of their creation // if they are no-longer needed if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { // ignore } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { // ignore } stmt = null; } }
如果是偶尔用一下Connection, 那么在使用后就关闭掉吧.
import java.sql.* ;// 主要功能就是连接数据库、关闭数据库
public class DataBaseConnection
{
private final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ;
private final String DBURL = "jdbc:oracle:thin:@localhost:1521:MLDN" ;
private final String DBUSER = "scott" ;
private final String DBPASSWORD = "tiger" ;
private Connection conn = null ; public DataBaseConnection()
{
try
{
Class.forName(DBDRIVER) ;
this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ;
}
catch (Exception e)
{
}
} // 取得数据库连接
public Connection getConnection()
{
return this.conn ;
} // 关闭数据库连接
public void close()
{
try
{
this.conn.close() ;
}
catch (Exception e)
{
}
}
};
不过orcl的连接就要谨慎了,最好做个连接池,可以使用Database connection pooling services.
DBCP这个类库已经比较稳定,参考http://commons.apache.org/dbcp/
以参考http://dev.mysql.com/doc/refman/5.0/en/connector-j-usagenotes-basic.html#connector-j-examples-connection-drivermanager
// assume that conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar"); // or alternatively, if you don't know ahead of time that
// the query will be a SELECT... if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
} // Now do something with the ResultSet ....
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { // ignore } rs = null;
} if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore } stmt = null;
}
}