本文共 1333 字,大约阅读时间需要 4 分钟。
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class OracleConnectionTest { private String url="jdbc:oracle:thin:@127.0.0.1:1521:YOOTK"; private String dbUsername="SCOTT"; private String dbPassword="tiger"; //注意要引入java.sql.Connection 而不是util包下的 private Connection conn=null; private Statement statement=null; private ResultSet rs=null; private String sql=""; public void selectTest(){ try { Class.forName("oracle.jdbc.OracleDriver"); conn=DriverManager.getConnection(url, dbUsername, dbPassword); sql="select * from emp"; statement=conn.createStatement(); rs=statement.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); }finally { try { if(rs==null) { rs.close(); } if(statement==null) { statement.close(); } if(conn==null) { conn.close(); } } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } public static void main(String[] args) { new OracleConnectionTest().selectTest(); }}
运行成功,控制台输出数据库EMP表第一列的所有值。
转载地址:http://lvkra.baihongyu.com/