java连接oracle数据库常用的三种方法

时间:2021-06-15 13:13:55

1.使用JDBC_ODBC桥连接方式

public static void main(String[] agrs) {
try {

// 1.加载驱动
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 2.得到链接 //your username and your password
Connection ct = DriverManager.getConnection("jdbc:odbc:texthx","scott", "123");
// sql severr 一样
Statement sm = ct.createStatement();
ResultSet rs = sm.executeQuery("select * from emp");

while (rs.next()) {
// 打印出用户名和薪水
System.out.println("用户名:" + rs.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
}

2.使用JDBC连接oracle 

<span style="font-size:14px;">try {
//1.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.连接数据库 </span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:12px;">//your username and your password </span></span><span style="font-size:14px;">
Connection ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","123");
//3.获得数据
Statement sm = ct.createStatement();

ResultSet rs = sm.executeQuery("select * from emp");

while (rs.next()) {

// 打印出用户名和薪水
System.out.println("用户名:" + rs.getString(2));

}

rs.close();
sm.close();
ct.close();
} catch (Exception e) {
e.printStackTrace();
}</span>

3.具体名字我也不好说,不过经常看到有人这么用。src源包下建立db.propertis.写下你的配置选项:

driver=oracle.jdbc.driver.OracleDriver
url=jdbc\:oracle\:thin\:@localhost\:1521\:orcl
username=scott
password=123

然后在程序中读取:

private static String username = null; 
private static String password = null ;
private static String driver = null ;
private static String url = null ;
static{
Properties ps = new Properties();
try {
ps.load(TextOrc3.class.getResourceAsStream("/db.properties"));
driver = ps.getProperty("driver");
url = ps.getProperty("url");
username = ps.getProperty("username");
password = ps.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}

public static Connection getConn(){
Connection conn = null ;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn ;
}
这种方法可能有人用,可能是想保证数据的安全性吧,毕竟这些数据表面上是不可见的。