下載ODBC Jar包驅動,網上百度下載或者去官網下載,導入到Eclipse 項目里面
建立連接
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( "------加載驅動成功-----" ); 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; } } |
查詢
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 ; } /* * 將查詢結果轉化為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(); } } |
1
2
3
4
|
//調用 String sql= "select * from table" ; String result=DbGetGps.select(sql); System.out.println(result); |
以上所述是小編給大家介紹的Java連接Oracle數據庫并查詢,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.2cto.com/database/201704/634183.html