本帖最后由 霍振鹏 于 2014-4-12 20:55 编辑
为什么会出现异常:- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public final class JDBCUtils {
- private static final String url = "jdbc:oracle:thin:@localhost:1521:orcl";
- private static final String user = "scott";
- private static final String pass = "tiger";
- static {
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private JDBCUtils() {
- }
- public static Connection getConnection() throws SQLException {
- return DriverManager.getConnection(url, user, pass);
- }
- public static void free(ResultSet rs, Statement sm, Connection conn) {
- try {
- if (rs != null) {
- rs.close();
- }
- } catch (SQLException e) {
- } finally {
- try {
- if (sm != null) {
- sm.close();
- }
- } catch (SQLException e) {
- } finally {
- try {
- if (conn != null) {
- conn.close();
- }
- } catch (SQLException e) {
- }
- }
- }
- }
- }
复制代码
- public class ConnectionOracle {
- /**
- * @param args
- */
- public static void main(String[] args) throws SQLException {
- // TODO Auto-generated method stub
- //selectStatement();
- createa();
- }
- static void createa() throws SQLException
- {
- Connection conn = null;
- Statement sm = null;
- ResultSet rs = null;
- try {
- conn = JDBCUtils.getConnection();
- // 创建语句
- sm = conn.createStatement();
- // 执行语句
- rs = sm.executeQuery("select name,age,address from student");//////这里最好写上列名,有时候数据库中的列有很多
-
- // 输出结果
- while (rs.next()) {
- // System.out.println(rs.getObject(1) + "\t" + rs.getObject(2)
- // + "\t" + rs.getObject(3));//////getObject方法还有另一种重载形式,传递的是一个String类型,就是要列的名字,这种方式更加易读
- System.out.println(rs.getObject("name")+"\t"+rs.getObject("age"));
- }
- } finally {
- JDBCUtils.free(rs, sm, conn);
- }
- }
复制代码
C:\Users\hupzhenpeng\Desktop\123654.png
C:\Users\hupzhenpeng\Desktop\456789.png
|
|