package com.shsxt.jdbcs; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; /*
* jdbc步骤: java连接数据库
* // 导入 jar包
* 1、加载驱动 数据库厂商提供的实现类
* 2、获取连接 提供 url 用户名 密码
* 3、创建处理块 可以发送SQL语句到服务器(数据库) 准备一条 SQL语句
* 4、结果集
* 5、分析结果集
* 6、释放资源 先开的后放, 后打开的先放
*/
public class Demo002JDBCConnect {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user= "scott";
String pwd= "tiger";
Connection conn = null;
Statement s = null;
ResultSet rs = null; try {
conn = DriverManager.getConnection(url, user, pwd);
s = conn.createStatement();
String sql = "select deptno, dname, loc from dept";
rs = s.executeQuery(sql);
while(rs.next()){
int deptno = rs.getInt(1); // 根据列号来获取值
String dname = rs.getString("dname"); // 根据列名来获取值
String loc = rs.getString(3);
System.out.println(deptno + "\t" + dname + "\t" + loc);
} } catch (SQLException e) {
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} if(s!=null){
try {
s.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } }
}