下載ODBC Jar包驅(qū)動,網(wǎng)上百度下載或者去官網(wǎng)下載,導(dǎo)入到Eclipse 項(xiàng)目里面
建立連接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class DbConn { 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( "------加載驅(qū)動成功-----" ); conn = (Connection) DriverManager.getConnection(url, user, password); Log.logD( "------連接成功-----" ); } catch (ClassNotFoundException e) { Log.logD( "------加載驅(qū)動失敗,驅(qū)動類未找到------" ); e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); Log.logD( "------加載驅(qū)動失敗------" ); } } public static Connection getConn(){ return conn; } } |
查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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 ; } /* * 將查詢結(jié)果轉(zhuǎn)化為json數(shù)組 需要導(dǎo)入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(); } } |
1
2
3
4
|
//調(diào)用 String sql= "select * from table" ; String result=DbGetGps.select(sql); System.out.println(result); |
以上所述是小編給大家介紹的Java連接Oracle數(shù)據(jù)庫并查詢,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.2cto.com/database/201704/634183.html