下载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