JDBC
1.JDBC1概述
**概述:**java数据库连接,(Java Database Connectivity,简称JDBC)是java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。
驱动: 两个设备之间通信的桥梁
1.1入门操作:
- 加载驱动
- 获得连接
- 基本操作(获得执行sql语句的对象 -> 编写sql语句 -> 执行sql语句 -> 遍历结果表)
- 释放资源
public class JDBCDemo {
@Test
public void demo() throws ClassNotFoundException, SQLException {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/web_test","root","123456");
//3.基本操作:执行sql语句
//3.1获得执行sql语句的对象
Statement statement = conn.createStatement();
//3.2编写sql语句
String sql = "select * from student";
//3.3执行sql语句
ResultSet rs = statement.executeQuery(sql);
//3.4遍历结果集
while (rs.next()){
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getInt("age")+" ");
System.out.print(rs.getString("name")+" ");
System.out.println();
}
//4释放资源
rs.close();
statement.close();
conn.close();
}
}
2.JDBC的API详解
2.1DriverManager
作用一:
- 注册驱动: registerDriver(Driver driver)
这个方法可完成驱动的注册,但是实际开发中不会使用,因为源代码中有静态代码块已经调用了注册驱动的方法。
应使用Class.forName(“com.mysql.jdbc.Driver”); 加载驱动
作用二:
- 获得连接: getConnection(String url,String ueser,String password)
该方法用来获得与数据连接:三个参数分别为(与数据库连接的路径,与数据库连接的用户名,与数据库连接的密码)
url的写法: jdbc:mysql://localhost:3306/web_test
- jdbc: 连接数据库的协议
- mysql : 是jdbc的子协议
- localhost : 连接的MySQl数据库服务器的主机地址(如果连接的是本机则可以写localhost,不是本机,就需要连接主机的ip地址)
- 3306: MySQL数据库服务器的端口号(一般都为3306)
- web_test: 数据库名称
若连接的是本机,则url可简化为: jdbc://mysql///web_test
2.2Connection
与数据库连接对象。
作用一:创建执行SQL语句的对象
- Statement createStatement(); 创建一个Statement对象来将SQL语句发送到数据库
- CallableStatement prepareCall(String sql); 创建一个CallableStatement对象来调用数据库存储过程
- PrepareStatement prepareStatement(String sql); 创建一个PrepareStatement对象来将参数化的SQL语句发送到数据库
Statement : 执行SQL
CallableStatement: 执行数据库中存储过程
PrepareStatement : 执行SQL对SQL进行预处理、解决SQL注入漏洞
作用二:管理事务
- void setAutoCommit(boolean autoCommit); 将此连接的自动提交模式设置为给定状态
- void commit(); 使所有上一次提交/回滚后进行的更改成为持久更改,并释放此Connection对象当前持有的所有数据库。
- void rollback(); 取消在当前事务中进行的所有更改,并释放此Connection对象当前所持有的所有数据库锁。
2.3.Statement
作用一:执行SQL语句
- boolean execute(String sql); 执行给定的SQL语句,并通知驱动程序所有自动生成的键都应该可用于获取.
- 执行查询,修改,田间,删除的SQL语句(有ResultSet返回则返回true,否则返回false)
- ResultSet executeQuery(String sql); 执行给定的SQL语句,该语句返回单个ResultSet对象
- 执行查询
- int executeUpdate(String sql);执行给定SQL语句,该语句可能为insert,update或delete,或者不返回任何内容的SQL语句.
- 执行修改,添加,删除SQL语句
作用二:执行批处理(了解)
- void addBatch(String sql); 将给定的SQL命令添加到此Statement对象的当前命令列表中
- void clearBatch(); 清空此Statement对象的当前SQL命令列表
- int []executeBatch(); 将一批命令提交给数据库来执行,如果全部命令执行成功,则返回更新计数组成的数组。
2.4.ResultSet: 结果集
通过select语句的查询结果(只有查询语句才有结果集)
结果集的遍历:
- boolean next(); 将光标从当前位置向前移一行。
while (rs.next()){
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getInt("age")+" ");
System.out.print(rs.getString("name")+" ");
System.out.println();
}
结果集的获取:
示例方法:
-
int getInt(int columnIndex); 以java编程语言中int的形式获取此ResultSet对象的当前行中指定列的值(列号)
-
int getInt(String columnLabel); 以java编程语言中int的形式获取ResultSet对象的当前行中指定列的值(列名)
-
getXXX(int columnIndex); getXXX(String columnName);
3.JDBC资源释放
JDBC程序执行结束后,将与数据库进行交互的对象释放掉1,通常是ResultSet,Statement,Connection。
这几个对象中尤其是Connection对象非常稀有。尽量做到晚创建
- 将资源释放的代码写到finally的代码块中
- 资源释放的代码应该写的标准
标准写法
finally {
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
rs = null;
}
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
statement = null;
}
if (conn!= null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
conn = null;
}
}
4.CRUD操作
4.1添加
public class JDBCAddDemo {
@Test
public void demo(){
Connection conn = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接
String url = "jdbc:mysql:///web_test?characterEncoding=utf8"; //指定utf8编码,防止插入中文时出错
String user = "root";
String pass = "123456";
conn = DriverManager.getConnection(url,user,pass);
//3.基本操作
statement = conn.createStatement();
String sql = "insert into student values(null,20,'楚狂');";
int num = statement.executeUpdate(sql);
if(num > 0){
System.out.println("插入成功!");
}
}catch (Exception e){
e.printStackTrace();
}finally {
//释放资源
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
statement = null;
if(conn !=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
conn = null;
}
}
}
4.2修改
public class JDBCUpdateDemo {
@Test
public void demo() {
Connection conn = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接
String url = "jdbc:mysql:///web_test?characterEncoding=utf8";
String user = "root";
String pass = "123456";
conn = DriverManager.getConnection(url,user,pass);
//3.基本操作
statement = conn.createStatement();
String sql = "update student set age = 99,name='李华' where id = 8";
int num = statement.executeUpdate(sql);
if (num>0){
System.out.println("修改成功!");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
//4.释放资源
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
statement = null;
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
conn=null;
}
}
}
}
4.3删除
public class JDBCDeleteDemo {
@Test
public void demo(){
Connection conn = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建连接
String url = "jdbc:mysql:///web_test?characterEncoding=utf8";
String user = "root";
String pass = "123456";
conn = DriverManager.getConnection(url,user,pass);
//3,基操
statement = conn.createStatement();
String sql = "delete from student where id = 7";
int num = statement.executeUpdate(sql);
if (num>0){
System.out.println("删除成功!");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
//4.释放资源
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
statement = null;
}
if (conn !=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
conn = null;
}
}
}
}
4.查询
查询多条数据
public class JDBCSelectDemo {
@Test
public void demo(){
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获得连接
String url = "jdbc:mysql:///web_test?characterEncoding=utf8";
String user = "root";
String pass = "123456";
conn = DriverManager.getConnection(url,user,pass);
//3.执行sql语句
stat = conn.createStatement();
String sql = "select * from student";
rs = stat.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getInt("age")+" "+rs.getString("name"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (rs!= null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
rs = null;
}
if (stat!= null){
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
stat = null;
}
if (conn!= null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
conn = null;
}
}
}
}
查询一条语句
@Test
public void demo1(){
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:///web_test?characterEncoding=utf8","root","123456");
stat = conn.createStatement();
String sql = "select * from student where id = 1";
rs = stat.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getInt("id")+" "+rs.getInt("age")+" "+rs.getString("name"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (rs != null)<