1. 安裝Oracle數據庫,我這里使用的是Oracle 12c
2. 創建Java工程 connection-oracle

注意:使用的JavaSE-1.8
3. 在Oracle的安裝目錄里,將djdbc8.jar 拷貝到java工程
路徑為:C:\app\oracle\product\12.2.0\dbhome_1\jdbc\lib

4. 創建連接Oracle的java類
public class OracleJdbcTest {
//數據庫連接對象
private static Connection conn = null;
private static String driver = "oracle.jdbc.driver.OracleDriver"; //驅動
private static String url = "jdbc:oracle:thin:@//127.0.0.1:1521/orcl"; //連接字符串
private static String username = "system"; //用戶名
private static String password = "123456"; //密碼
// 獲得連接對象
private static synchronized Connection getConn(){
if(conn == null){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
//執行查詢語句
public void query(String sql, boolean isSelect) throws SQLException{
PreparedStatement pstmt;
try {
pstmt = getConn().prepareStatement(sql);
//建立一個結果集,用來保存查詢出來的結果
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
System.out.println(name);
}
rs.close();
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void query(String sql) throws SQLException{
PreparedStatement pstmt;
pstmt = getConn().prepareStatement(sql);
pstmt.execute();
pstmt.close();
}
//關閉連接
public void close(){
try {
getConn().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5. 創建調用類
public class ConnOracle {
public static void main(String[] args) throws SQLException {
OracleJdbcTest test = new OracleJdbcTest();
try {
test.query("drop table student");
} catch (SQLException e) {}
test.query("create table student(id int, name nchar(20))");
test.query("insert into student values(1,'zhangsan')");
test.query("insert into student values(2,'lisi')");
test.query("select * from student", true);
test.close();
}
}
6. 顯示結果

