Java JDBC连接Oracle

1. 安装Oracle数据库,我这里使用的是Oracle 12c

2. 创建Java工程 connection-oracle

Java JDBC连接Oracle

注意:使用的JavaSE-1.8

3. 在Oracle的安装目录里,将djdbc8.jar 拷贝到java工程

路径为:C:\app\oracle\product\12.2.0\dbhome_1\jdbc\lib

Java JDBC连接Oracle

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. 显示结果

Java JDBC连接Oracle

上一篇:from提交数据,高级选择器,伪类选择器,前端样式等


下一篇:ajax读取文本内容(此处的txt文件和html文件处于同级目录)