定义了操作所有关系型数据库的规则
作用:用java语言操作数据库
接口或类 | 作用 |
---|---|
DriverManger类 | 1.管理与注册数据库驱动 2.得到数据库连接对象 |
Connection接口 | 连接对象,用于创建Statement和PreparedStatement对象 |
Statement接口 | SQL语句对象,用于将SQL语句发送给数据库服务器 |
PreparedStatement接口 | SQL语句对象,Statement的子接口 |
ResultSet接口 | 封装数据库查询到的结果集,返回给java程序 |
JDBC使用步骤:
实现代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student","root","root");
//sql语句
String sql = "update class_1 set math = 60 where id < 3";
//获取执行sql语句的对象statement
Statement statement = connection.createStatement();
//执行sql语句,返回影响的行数
int count = statement.executeUpdate(sql);
System.out.println(count);
//释放资源
connection.close();
statement.close();
}
}
详解各个对象
驱动管理对象
功能:
方法:static void registerDriver(Driver driver)
:
功能:注册与给定驱动程序DriverManager。
写代码使用:Class.forName("com.mysql.jdc.Driver");
注意:mysql 1.5之后的jar包可以省略注册驱动的步骤
方法:static Connection getConnection(String url,String user,String password)
参数:
数据库连接对象
功能:
获取执行sql的对象
Statement createStatement()
PreparedStatement prepareStatement(String sql)
管理事务
开启事务:setAutoCommit(boolean autoCommit)
调用该方法设置参数为false,即开启事务
提交事务:commit()
回滚事务:rollback()
执行sql的对象
方法声明 | 功能描述 |
---|---|
boolean execute(String sql) | 执行任意的sql |
int executeUpdate(String sql) | 执行DML与DDL语句,返回影响行数,返回值<0则失败 |
ResultSet executeQuery(String sql) | 执行DQL语句 |
结果集对象,封装查询结果
boolean next()
:游标向下移动一行,判断当前行是否是最后一行,如果是,返回false,如果不是,返回true。
getXxx(参数)
:获取数据
实例代码1
import java.util.Date;
/*将class_1表的封装成类*/
@SuppressWarnings("all")
public class Class_1 {
private int id;
private String name;
private int age;
private String classroom;
private double english;
private double chinese;
private double math;
private Date recordtime;
private int lesson;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getChinese() {
return chinese;
}
public void setChinese(double chinese) {
this.chinese = chinese;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public Date getRecordtime() {
return recordtime;
}
public void setRecordtime(Date recordtime) {
this.recordtime = recordtime;
}
public int getLesson() {
return lesson;
}
public void setLesson(int lesson) {
this.lesson = lesson;
}
@Override
public String toString() {
return "Class_1{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", classroom='" + classroom + '\'' +
", english=" + english +
", chinese=" + chinese +
", math=" + math +
", recordtime=" + recordtime +
", lesson=" + lesson +
'}';
}
}
实例代码2
/*
* 需求:查询class_表中的信息
* */
public class JDBCDemo1 {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Class_1 class_1;
List<Class_1> list = new ArrayList<>();
public static void main(String[] args) {
List<Class_1> all = new JDBCDemo1().findAll();
for (Class_1 person : all) {
System.out.println(person);
}
}
public List<Class_1> findAll(){
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Student","root","root");
statement = connection.createStatement();
String sql = "select * from class_1";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
//将数据库里的数据记录提取出来
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String classroom = resultSet.getString("class");
double english = resultSet.getDouble("english");
double chinese = resultSet.getDouble("chinese");
double math = resultSet.getDouble("math");
Date recordtime = resultSet.getDate("recordtime");
int lesson = resultSet.getInt("lesson");
//创建表类对象
class_1 = new Class_1();
class_1.setId(id);
class_1.setName(name);
class_1.setAge(age);
class_1.setClassroom(classroom);
class_1.setEnglish(english);
class_1.setChinese(chinese);
class_1.setMath(math);
class_1.setRecordtime(recordtime);
class_1.setLesson(lesson);
list.add(class_1);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e){
e.printStackTrace();
}finally {
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
作用:简化书写
实例代码
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 {
try {
//创建Properties集合类
Properties properties = new Properties();
//获取src路径下的文件方式
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resource = classLoader.getResource("mysql.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");
//注册驱动
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* 释放资源
* @param connection
* @param statement
* @param resultSet
*/
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
properties文件
url = jdbc:mysql://localhost:3306/Student
user = root
password = root
driver = com.mysql.jdbc.Driver
Statement接口的子接口
作用:执行sql的对象,解决SQL注入问题
注意:后期都会使用PreparedStatement来完成增删改查的所有操作
实例代码
import Utils.JDBCUtils;
import java.sql.*;
import java.util.Scanner;
@SuppressWarnings("all")
public class JDBCDemo2 {
String user,password;
Connection connection = null;
PreparedStatement ppst = null;
ResultSet resultSet = null;
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String user = scanner.nextLine();
System.out.println("请输入密码");
String password = scanner.nextLine();
boolean flag = new JDBCDemo2().login(user, password);
System.out.println(flag ? "登录成功":"用户名或密码错误");
}
public boolean login(String user,String password){
if(user == null || password == null){
return false;
}
try {
Connection connection = JDBCUtils.getConnection();
String sql = "select * from acount where user = ? and password = ?";
ppst = connection.prepareStatement(sql);
ppst.setString(1,user);
ppst.setString(2,password);
resultSet = ppst.executeQuery();
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JDBCUtils.close(connection,ppst,resultSet);
}
return false;
}
}
事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
操作:
使用Connection对象来管理事务
setAutoCommit(boolean autoCommit)
:调用该方法设置参数为false,即开启事务
commit()
rollback()
实例代码
import Utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@SuppressWarnings("all")
public class JDBCDemo3 {
Connection connection = null;
PreparedStatement ppst1 = null,ppst2 = null;
public static void main(String[] args) {
new JDBCDemo3().transfer();
}
public void transfer(){
try {
connection = JDBCUtils.getConnection();
connection.setAutoCommit(false);
String sql1 = "update account set balance = balance - ? where name = ?";
String sql2 = "update account set balance = balance + ? where name = ?";
ppst1 = connection.prepareStatement(sql1);
ppst2 = connection.prepareStatement(sql2);
ppst1.setInt(1,500);
ppst1.setString(2,"Lisi");
ppst2.setInt(1,500);
ppst2.setString(2,"AFan");
ppst1.executeUpdate();
ppst2.executeUpdate();
connection.commit();
} catch (Exception e) {
e.printStackTrace();
if(connection!=null){
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}finally {
JDBCUtils.close(connection,ppst1);
JDBCUtils.close(null,ppst2);
}
}
}
概念:容器(集合),存放数据库连接的容器。当系统初始化好后,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。
优点:
javax.sql包下的
方法:
方法声明 | 功能描述 |
---|---|
Connection getConnection() | 获取链接 |
void close() | 如果连接对象Connection是从连接池中获取,则不会关闭连接,而是归还连接。 |
此接口一般由数据库厂商来实现
数据库连接池技术
使用步骤:
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.12.jar
。
ComboPoolDataSource
getConnection()
//1.利用多态创建数据库连接池对象
DataSource ds = new ComboPoolDataSource();
//2.获取连接对象
Connection connection = ds.getConnection()
数据库连接池技术,阿里巴巴提供
使用步骤:
导入jar包 druid-1.0.9.jar
定义配置文件:
加载配置文件
获取数据库连接池对象:通过工厂来获取DruidDataSourceFactory
获取连接getConnection()
//3.加载配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
Connection connection = ds.getConnection();
定义工具类
JDBCUtils工具类实例代码
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
@SuppressWarnings("all")
public class JDBCUtils {
private static DataSource ds = null;
static {
try {
//1.加载配置文件
Properties properties = new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(is);
//2.获取DataSource对象
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取链接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(Connection connection){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Spring框架中对jdbc的简单封装
使用步骤:
使用步骤:
导入jar包
创建JdbcTemplate对象,依赖于数据源DataSource
JdbcTemplate template = new JdbcTemplate(ds)
JdbcTemplate方法来完成CRUD的操作
方法声明 | 功能描述 |
---|---|
int update(String sql) | 执行DML语句 |
Map< String , Object > queryForMap(String sql) | 查询结果将结果封装为map集合,列名为key,将值作为value将这条记录封装为一个map集合,方法查询的结果集长度和只能为1 |
List | 查询结果将结果集封装成list集合 |
List query(String sql,参数) | 查询结果,将结果封装为JavaBean对象 参数:RowMapper类型,一般使用new BeanPropertyRowMapper<类型>(类型.class)完成数据到JavaBean的自动封装 |
queryForObject(String sql,参数) | 查询结果,将结果封装成对象,一般用于聚合函数的查询 |