- package com.yj.demo;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class DbFactory {
- //连接数据库的核心api对象
- private Connection conn = null;
- private ResultSet rs = null;
- private PreparedStatement pstmt = null;
- private void getConnection() {
- //连接数据库的可配置属性
- String driver = "oracle.jdbc.driver.OracleDriver";
- String url = "jdbc:oracle:thin:@10.0.2.168:1521:orcl";
- String username = "scott";
- String password = "tiger";
- try {
- //加载驱动程序
- Class.forName(driver);
- //获得数据库连接
- conn = DriverManager.getConnection(url, username, password);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- //无结果返回的数据库操作方法,参数sql为sql语句,参数params为sql语句中的参数
- public void execSqlWithoutResult(String sql, Object[] params) {
- try {
- if (conn == null) {
- getConnection();
- }
- pstmt = conn.prepareStatement(sql);
- for (int i = 0; i < params.length; i++) {
- pstmt.setObject(i + 1, params[i]);
- }
- pstmt.execute();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- //有结果返回的数据库操作方法,参数意义同上
- public ResultSet execSqlWithResult(String sql, Object[] params) {
- try {
- if (conn == null) {
- getConnection();
- }
- pstmt = conn.prepareStatement(sql);
- for (int i = 0; i < params.length; i++) {
- pstmt.setObject(i + 1, params[i]);
- }
- rs = pstmt.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return rs;
- }
- //关闭连接
- public void close() {
- try {
- if(rs != null){
- rs.close();
- }
- if(pstmt != null){
- pstmt.close();
- }
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/130620149773.html
来源: http://www.codesnippet.cn/detail/130620149773.html