JDBC API
主要功能:与数据库建立连接、执行SQL 语句、处理结果
DriverManager :依据数据库的不同,管理JDBC驱动
语法:Class.forName(JDBC驱动类);
Connection :负责连接数据库并担任传送数据的任务
语法:conn=DriverManager.getConnection(URL,数据库用户名,密码);
Statement :由 Connection 产生、负责执行SQL语句
ResultSet:负责保存Statement执行后所产生的查询结果
注意导入ojdbc.jar包
步骤:
1、加载JDBC驱动
2、与数据库建立连接
3、发送SQL语句,并得到返回结果
4、处理返回结果
5、释放资源
例子:
public class test01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn=null;
PreparedStatement pre=null;
// 加载Oracle驱动程序
Class.forName("oracle.jdbc.OracleDriver");
//连接数据库
conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","admin");
//准备sql语句
String sql = "insert into dept values(22,'xx','xx')";
// 实例化预编译语句
pre = conn.prepareStatement(sql);
//执行
pre.executeUpdate();
System.out.println("ok");
//关闭资源
pre.close();
conn.close();
}
}
注意关闭顺序,先打开的后关闭
Statement常用方法
注意:
查询语句用 executeUpdate();
增,删,改语句用executeQuery();
ResultSet常用方法
例子:
public class test01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection conn=null;
PreparedStatement pre=null;
ResultSet res = null;
// 加载Oracle驱动程序
Class.forName("oracle.jdbc.OracleDriver");
//连接数据库
conn=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","admin");
//准备sql语句
String sql = "select * from dept";
// 实例化预编译语句
pre = conn.prepareStatement(sql);
//执行,获取结果集
res = pre.executeQuery();
//遍历结果集
while(res.next()){
int deptno =res.getInt(1);
String dname = res.getString(2);
String dlc = res.getString(3);
System.out.println(deptno+"--"+dname+"--"+dlc);
}
//关闭资源
res.close();
pre.close();
conn.close();
}
}
PreparedStatement 接口
避免SQL注入的隐患
继承自 Statement接口
比Statement对象使用起来更加灵活,更有效率
例子:
Connection conn = null;
PreparedStatement pstmt = null;//声明PreparedStatement变量
…
// 建立连接
… …
// 更新狗狗信息到数据库
String sql="update dog set health=?,love=? where id=?";//使用占位符的SQL语句
pstmt = conn.prepareStatement(sql);创建PreparedStatement对象
//设置每个输入参数的值,按?顺序分别赋值
pstmt.setInt(1, 80);
pstmt.setInt(2, 15);
pstmt.setInt(3, 1);
pstmt.executeUpdate();//执行SQL语句
… …
pstmt.close();
conn.close();