转载地址:https://blog.csdn.net/suwu150/article/details/52744952
JDBC编程的六个步骤:
准备工作中导入ojdbc文件,然后右键选中添加路径
build path-->到oracle安装目录里添加oracle的ojdbc.jar包
(1).加载Driver类,注册数据库驱动;
Class.forName("oracle.jdbc.OracleDriver");
(2).通过DriverManager,使用url,用户名和密码建立连接(Connection);
String url = "jdbc:oracle:thin:@localhost:1521:xe";//其中xe为sid
String user = "XXX";
String password = "XXX";
Connection conn = DriverManager.getConnection(url,name,password);
(3).通过Connection,使用sql语句打开Statement对象;
Statement state = conn.createStatement();
(4).执行语句,将结果返回resultSet;
String sql = "select id,name from s_emp"; //"insert into s_emp(id,name) values(12,'zhangsan')";
ResultSet rs = state.executeQuery(sql);
(5).处理结果集
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString(2);
System.out.println(id+" "+name);
}
(6).倒叙释放资源resultSet-》preparedStatement-》connection。
rs.close();
state.close();
conn.close();
如下面所示代码,实现插入操作
public void test_insert() { String driver="oracle.jdbc.driver.OracleDriver"; String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";//orcl为sid String user="briup"; String password="briup"; Connection conn=null; Statement stat=null; try { //1、注册驱动 Class.forName(driver); //2、获取连接 conn= DriverManager.getConnection(url, user, password); //System.out.println(conn); //3、创建statement对象 stat=conn.createStatement(); //4、执行sql语句 String sql="insert into lover values(5,'suxingxing',to_date('21-9-2016','dd-mm-yyyy'))"; stat.execute(sql); //System.out.println(stat.execute(sql)); //5、处理结果集,如果有的话就处理,没有就不用处理,当然insert语句就不用处理了 } catch (Exception e) { e.printStackTrace(); } finally{ //6、关闭资源 try { if(stat!=null)stat.close(); } catch (SQLException e) { e.printStackTrace(); } try { if(conn!=null)conn.close(); } catch (SQLException e) { e.printStackTrace(); } }