jdbc 和oracle数据库 建立连接

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestOracle {

public static void main(String[] args) {
//1.加载驱动
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.OracleDriver");

//2.建立连接
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
conn = DriverManager.getConnection(url, "scott", "tiger");

//3.发送SQL语句,获得结果
String sql = "select * from emp";
ps = conn.prepareStatement(sql);

rs = ps.executeQuery();

//4.处理结果
while(rs.next()) {
System.out.println(rs.getString("ename"));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//5.释放资源
try {
if(conn != null) conn.close();
if(ps != null) ps.close();
if(rs != null) rs.close();
} catch (Exception e2) {
e2.printStackTrace();
}

}
}

}

上一篇:杨辉三角(java)


下一篇:程序员面试金典-面试题 01.04. 回文排列