如何用java连接oracle数据库
发布网友
发布时间:2022-04-20 11:16
我来回答
共2个回答
懂视网
时间:2022-04-07 21:10
import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6
7 /**
8 * oracle数据库驱动类 封装
9 * @author Administrator
10 *
11 */
12 public class Oracle {
13
14 final String Driver="oracle.jdbc.driver.OracleDriver"; //oracle驱动
15 final String url="jdbc:oracle:thin:@localhost:1521:orcl"; //1521:端口 orcl:数据库名
16 final String username="News"; //oracle数据库用户名
17 final String password="197520"; //oracle数据库密码
18
19 /*
20 * 封装连接
21 */
22 public Connection getConnection(){
23 Connection cn=null; //声明驱动
24
25 try {
26
27 Class.forName(Driver);//加载驱动
28
29 cn=DriverManager.getConnection(url,username,password);//建立连接
30
31 } catch (ClassNotFoundException e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 } catch (SQLException e) {
35 // TODO Auto-generated catch block
36 e.printStackTrace();
37 }
38 return cn;
39 }
40
41 /*
42 * 关闭结果集,操作,连接
43 */
44
45 public void Close(ResultSet rs,PreparedStatement ps,Connection cn){
46 try{
47 //判定是否为空值
48 if(rs!=null){
49 rs.close();
50 }
51 if(ps!=null){
52 ps.close();
53 }
54 if(cn!=null){
55 cn.close();
56 }
57 }catch(SQLException e){
58 e.printStackTrace();
59 }
60 }
61
62 }
Java连接Oracle数据库
标签:
热心网友
时间:2022-04-07 18:18
public class OracleJdbcTest
{
String driverClass = "oracle.jdbc.driver.OracleDriver";
Connection con;
public void init(FileInputStream fs) throws Exception
{
Properties props = new Properties();
props.load(fs);
String url = props.getProperty("db.url");
String userName = props.getProperty("db.user");
String password = props.getProperty("db.password");
Class.forName(driverClass);
con=DriverManager.getConnection(url, userName, password);
}
public void fetch() throws SQLException, IOException
{
PreparedStatement ps = con.prepareStatement("select SYSDATE from al");
ResultSet rs = ps.executeQuery();
while (rs.next())
{
// do the thing you do
}
rs.close();
ps.close();
}
public static void main(String[] args)
{
OracleJdbcTest test = new OracleJdbcTest();
test.init();
test.fetch();
}
}
[代码] db.properties
db.url = jdbc:oracle:thin:@::
db.user = sa
db.password =