先来回顾一下JDBC的六个步骤:
1.加载驱动
String DRIVER = "oracle.jdbc.OracleDriver"; Class.forName(DRIVER );
2.建立和数据库的连接
String URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; String USER = "SCOTT"; String PASSWORD = "TIGER"; Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
3.创建语句对象
String sql = "SELECT * FROM emp"; PreparedStatement pstm = connection.prepareStatement(sql);
4.执行SQL语句
ResultSet rs = pstm.executeQuery();
5.处理结果
6.释放资源
以Oracle中自带的emp表为例,展示如何用JDBC查询并展示数据:
<%@page import="java.sql.*"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="io.zhangjia.test.Book"%> <%@ page import="java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> table { width: 40%; border: 1px #000 solid; border-spacing: 0; /*设置相邻单元格的边框间的距离为0*/ border-collapse: collapse; /*合并边框*/ } td, th { border: 1px #000 solid; } </style> <title>Insert title here</title> </head> <body> <% String DRIVER = "oracle.jdbc.OracleDriver"; String URL = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; String USER = "SCOTT"; String PASSWORD = "TIGER"; Class.forName(DRIVER); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); String sql = "SELECT * FROM emp"; PreparedStatement pstm = connection.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); %> <table> <tr> <th>EMPNO</th> <th>ENAME</th> <th>JOB</th> <th>MGR</th> <th>HIREdATE</th> <th>SAL</th> <th>COMM</th> <th>DEPTNO</th> </tr> <% while(rs.next()) { %> <tr> <!-- 注意下标不是从0开始,而是从1开始 --> <td><%= rs.getObject(1) %></td> <td><%= rs.getObject(2) %></td> <td><%= rs.getObject(3) %></td> <td><%= rs.getObject(4) %></td> <td><%= rs.getObject(5) %></td> <td><%= rs.getObject(6) %></td> <td><%= rs.getObject(7) %></td> <td><%= rs.getObject(8) %></td> </tr> <% } %> </table> <% rs.close(); pstm.close(); connection.close(); %> </body> </html>
请登录之后再进行评论