Java连接Oracle数据库 并查询

Java连接Oracle


下载ODBC Jar包驱动,网上百度下载或者去官网下载,导入到Eclipse 项目里面


建立连接

public class DbConn {
    private static String driver = "oracle.jdbc.driver.OracleDriver";
    private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    private static String user = "root";
    private static String password = "root";
    private static Connection conn = null;
    static {
        try {
            Class.forName(driver);
            Log.logD("------加载驱动成功-----");
            conn = (Connection) DriverManager.getConnection(url, user, password);
            Log.logD("------连接成功-----");
        } catch (ClassNotFoundException e) {
            Log.logD("------加载驱动失败,驱动类未找到------");
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
            Log.logD("------加载驱动失败------");
        }
    }

     public static Connection getConn(){
         return conn;
     }
}

查询

public class DbGetCan {
    private static PreparedStatement pstmt;
    private static ResultSet rs;
    private static  Connection conn;
    public static String select(String sql) {
        conn=DbConn.getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            return getJsonArray();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 将查询结果转化为json数组 需要导入Json jar包
     */
    public static String getJsonArray() throws SQLException, JSONException {
        JSONArray jsonArray=new JSONArray();
        ResultSetMetaData metaData = (ResultSetMetaData) rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {
            JSONObject jsonData = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnLabel(i);
                String value = rs.getString(columnName);
                jsonData.put(columnName, value);
            }
            jsonArray.put(jsonData);
        }
        rs.close();
        pstmt.close();
        return jsonArray.toString();

    }
}
//调用
String sql="select * from table";
String result=DbGetGps.select(sql);
System.out.println(result);

运行就可以了

你可能感兴趣的:(JAVA)