当前位置: 首页 > >

java 连接oracle查询,Java连接Oracle数据库并查询

发布时间:

下载odbc jar包驱动,网*俣认略鼗蛘呷ス偻略兀既氲絜clipse 项目里面


建立连接


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


运行就可以了


希望与广大网友互动??


点此进行留言吧!



友情链接: