连接Oracle数据库的步骤
0.导入ojdbc的jar包
1.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
2.建立连接
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","briup","briup")
3.创建搬运工
String sqls = "insert into student(id,name,age) values(1,'zhangsan',22)";
Statement stmt = conn.createStatement();
String sql = "insert into student(id,name,age) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1);
ps.setString(2,"zhangsan");
ps.setInt(3,22);
4.执行sql语句
stmt.execute(sql);
ps.execute();
5.如果有结果集的话处理结果集
String sql2 = "select * from student";
RusultSet rs = stmt.executeQuery(sql);
Student s = null;
List<Student> list = new ArrayList<Student>();
while(rs.next()){
int id = rs.getInt(1); //代表查出来的视图的第一列,或者使用select查出来的视图的列名
String name = rs.getName("name");
int age = rs.getInt(3);
s = new Student(id,name,age); //将查出来的数据封装成java中的对象
list.add(s);
}
6.关闭资源(先开的后关)
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();
0.导入ojdbc的jar包
1.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
2.建立连接
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:xe","briup","briup")
3.创建搬运工
String sqls = "insert into student(id,name,age) values(1,'zhangsan',22)";
Statement stmt = conn.createStatement();
String sql = "insert into student(id,name,age) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1,1);
ps.setString(2,"zhangsan");
ps.setInt(3,22);
4.执行sql语句
stmt.execute(sql);
ps.execute();
5.如果有结果集的话处理结果集
String sql2 = "select * from student";
RusultSet rs = stmt.executeQuery(sql);
Student s = null;
List<Student> list = new ArrayList<Student>();
while(rs.next()){
int id = rs.getInt(1); //代表查出来的视图的第一列,或者使用select查出来的视图的列名
String name = rs.getName("name");
int age = rs.getInt(3);
s = new Student(id,name,age); //将查出来的数据封装成java中的对象
list.add(s);
}
6.关闭资源(先开的后关)
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();