Oracle jdbc 连接

 

 

所需jar包:

ojdbc6.jar

下载地址:https://download.csdn.net/download/xc_oo0/10897959

 

示例代码:

package cnblogs.com.ooo0.oracle;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class OperateOracle {

    // 定义连接所需的字符串
    // 127.0.0.1是本机地址(要改成自己的IP地址),1521端口号,XE是精简版Oracle的默认数据库名
    private static String USERNAMR = "system";
    private static String PASSWORD = "123456";
    private static String DRVIER = "oracle.jdbc.OracleDriver";
    private static String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";// loc(本地)

    // 创建一个数据库连接
    Connection connection = null;
    // 创建预编译语句对象,一般都是用这个而不用Statement
    PreparedStatement pstm = null;
    // 创建一个结果集对象
    ResultSet rs = null;

    /**
     * 获取Connection对象
     * 
     * @return
     */
    public Connection getConnection() {
        if (connection == null) {
            synchronized (OperateOracle.class) {
                if (connection == null) {
                    try {
                        Class.forName(DRVIER);
                        connection = DriverManager.getConnection(URL, USERNAMR, PASSWORD);
                        // System.out.println("成功连接数据库");
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("class not find !", e);
                    } catch (SQLException e) {
                        throw new RuntimeException("get connection error!", e);
                    }
                }
            }
        }
        return connection;
    }

    /**
     * 释放资源
     */
    public void ReleaseResource() {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        OperateOracle oo = new OperateOracle();
        oo.selectData();
    }

    /**
     * 向数据库中查询数据
     */
    public void selectData() {
        connection = getConnection();
        String sql = "select * from users";
        try {
            pstm = connection.prepareStatement(sql);
            rs = pstm.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt("id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ReleaseResource();
        }
    }

}

 

posted @ 2019-01-05 17:31  草木物语  阅读(4489)  评论(0编辑  收藏  举报