JDBC概念
- JAVA DATABASE CONNECTIVITY java数据库连接
- JDBC本质:是官方(sun公司)定义的一套操作所有关系型数据库的规则(接口)。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类
快速入门
- 导入驱动jar包
①复制jar包到项目的libs目录下
②右键->add as library - 注册驱动
- 获取数据库的连接对象Connection
- 定义sql语句
- 获取执行sql语句的对象 Statement
- 执行sql,接收返回的结果
- 处理结果
- 释放资源
public class jdbcDemo1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1.导入jar包
// 2.注册驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 3.获取数据库连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4?characterEncoding=utf-8&useSSL=false&&serverTimezone = GMT", "root", "545267257zzt");
// 4.定义sql语句
String sql = "update class set name = '1' where cid =1 ";
// 5. 获取执行sql语句的对象
2020-08-14JDBC
同步滚动:
JDBC概念
JAVA DATABASE CONNECTIVITY java数据库连接
JDBC本质:是官方(sun公司)定义的一套操作所有关系型数据库的规则(接口)。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口(JDBC)编程,真正执行的代码是驱动jar包中的实现类
快速入门
导入驱动jar包
①复制jar包到项目的libs目录下
②右键->add as library
注册驱动
获取数据库的连接对象Connection
定义sql语句
获取执行sql语句的对象 Statement
执行sql,接收返回的结果
处理结果
释放资源
public class jdbcDemo1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1.导入jar包
// 2.注册驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 3.获取数据库连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4?characterEncoding=utf-8&useSSL=false&&serverTimezone = GMT", "root", "545267257zzt");
// 4.定义sql语句
String sql = "update class set name = '1' where cid =1 ";
// 5. 获取执行sql语句的对象
Statement statement = connection.createStatement();
// 6.执行sql
int i = statement.executeUpdate(sql);
// 7. 处理结果
System.out.println(i);
// 8. 释放资源
connection.close();
statement.close();
}
}
Statement statement = connection.createStatement();
// 6.执行sql
int i = statement.executeUpdate(sql);
// 7. 处理结果
System.out.println(i);
// 8. 释放资源
connection.close();
statement.close();
}
}
详解对象
DriverManager:驱动管理对象
功能:
- 注册驱动:告诉程序该使用哪个数据库的jar
真正进行注册是的java.sql.DriverManager.registerDriver()
但是通过反射Class.forName()将com.mysql.jc.jdbc.driver加载到内存,自动执行了包含java.sql.DriverManager.registerDriver()的静态代码块 - 获得数据库连接
url:jdbc:mysql://ip地址:端口号/数据库名称
user:用户名
password:密码
Connection:数据库连接对象
功能
- 获得执行sql的对象
Statement createStatement()
PreparedStatement prepareStatement(String sql) - 管理事务
开启事务:setAutoCommit(boolean autoCommit): 调用改方法设置参数未false,即开始事务
回滚事务:rollback()
提交事务:commit()
Statement:执行静态sql语句并返回其生成的结果的对象
- int excuteUpdate(String sql):执行DML,DDL语句(增删改语句,对数据库和数据表的操作);返回的int是受sql执行影响的行数
- ResultSet excuteQuery(String sql):执行DQL语句,返回结果集
public class jdbcDemo2 {
public static void main(String[] args) {
Connection conn = null;
Statement statement = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获得连接对象jdbc:mysql://localhost:3306/db4?characterEncoding=utf-8
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4?useSSL=false&serverTimezone=GMT", "root", "545267257zzt");
//3.获取statement执行sql的对象
statement = conn.createStatement();
//4.定义sql语句
String sql = "update class set name = '高二1班' where cid = 1";
//5.执行sql语句,获得结果
int i = statement.executeUpdate(sql);
//6.操作结果
System.out.println(i);
if (i==1){
System.out.println("执行成功");
}else{
System.out.println("执行失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
ResultSet:结果集对象,封装查询结果
- next():游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是,则返回false,如果不是则返回true
- getXxx(参数):获取数据,Xxx是数据类型,参数如果是int值表示是列的编号,参数如果是string代表列的名称
遍历结果集
where(result.next()!=false){
int i = result.getInt("id");
String name = result.getString("name");
}
public class jdbcDemo5 {
public static void main(String[] args) {
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db4?useSSL=false&serverTimezone=GMT", "root", "545267257zzt");
statement = conn.createStatement();
String sql = "select t1.id as id,t1.name as name,t2.name as class from student t1,class t2 where t1.cid = t2.cid";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String aClass = resultSet.getString("class");
System.out.println(id + "--------" + name + "----------" + aClass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement!=null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
PreparedStatement:执行sql的对象,解决sql注入问题
①SQL注入:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题
②预编译sql:参数使用?作为占位符,使用时给?赋值
PreparedStatement ps =connection.prepareStatement(String sql);
setXxx(参数1,参数2):参数1是?的位置,参数2是传入的值
ResultSet resultSet = ps.excuteQuery();
JDBC工具类
package cn.it.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class jdbcUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
//读取资源问价,获取值
static {
//读取文件
Properties properties = new Properties();
try {
//获取src路径下的文件的方法 ClassLoader类加载器
ClassLoader classLoader = jdbcUtils.class.getClassLoader();
URL resource = classLoader.getResource("jdbc.properties");
String path = resource.getPath();
properties.load(new FileReader(path));
url=properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
driver=properties.getProperty("driver");
} catch (IOException e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() {
Connection connection=null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//资源释放
public static void close(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
url=jdbc:mysql://localhost:3306/db4?useSSL=false&serverTimezone=GMT
user=root
password=545267257zzt
driver=com.mysql.cj.jdbc.Driver
JDBC控制事务
- 使用Connection对象来管理事务
①开启事务:setAutoCommit(boolean autoCommit):调用该方法设置参数是false,开启事务
②回滚事务:rollback()
③提交事务:commit() - 使用事务实现转账的案例
package cn.it.jdbc;
import cn.it.util.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class jdbcDemo6 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement1 = null;
try {
connection = jdbcUtils.getConnection();
String sql1 = "update account set balance = balance + ? where id = ?";
String sql2 = "update account set balance = balance - ? where id = ?";
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.setInt(1, 500);
preparedStatement.setInt(2, 1);
preparedStatement1 = connection.prepareStatement(sql2);
preparedStatement1.setInt(1, 500);
preparedStatement1.setInt(2, 2);
connection.setAutoCommit(false);
int i = preparedStatement.executeUpdate();
int i1 = preparedStatement1.executeUpdate();
//认为制造异常
int ii=3/0;
//事务提交要放到最后
connection.commit();
} catch (Exception e) {
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}
jdbcUtils.close(preparedStatement, connection);
jdbcUtils.close(preparedStatement1, connection);
}
}