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);

运行就可以了

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐