/** * 驱动加载字符串 */ private String className = "oracle.jdbc.driver.OracleDriver"; /** * 数据库连接地址 */ private String url="jdbc:oracle:thin:@localhost:1521:orcl"; /** * 登录名 */ private String user = "system"; /** * 密码 */ private String password="orcl"; /** * 数据库连接对象 */ protected Connection connection; /** * sql语句执行命令对象 */ protected PreparedStatement preparedStatement; /** * 结果集对象 */ protected ResultSet resultSet; /** * 获得数库连接 * @return 数据库连接对象 */ protected Connection openConnection(){ try { //加载驱动 Class.forName(className); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //获得数据库连接 try { this.connection = DriverManager.getConnection(url, user, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.connection; } protected void closeConnection(){ if(this.resultSet!=null){ try { //关闭结果集 this.resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(this.preparedStatement!=null){ //关闭sql执行对象 try { this.preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(this.connection!=null){ //关闭连接 try { this.connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
java jdbc连接oracle数据库_Java中使用JDBC连接oracle数据库
最新推荐文章于 2024-02-29 20:05:18 发布
这段代码展示了如何使用Java连接Oracle数据库,包括加载驱动、建立连接、执行SQL语句和处理结果集。在`openConnection`方法中,通过`Class.forName`加载驱动并用`DriverManager.getConnection`创建连接。在`closeConnection`方法中,依次关闭结果集、预编译语句和数据库连接,确保资源释放。
摘要由CSDN通过智能技术生成