JDBC
1.JDBC基本概念
概念:Java DataBase Connectivity Java 数据库连接,Java语言操作数据库。
JDBC本质:其实是官方(sun)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现这套接口,提供数据库驱动jar包。我们可以使用这套接口编程,真正执行的代码是驱动jar包中的实现类。
2.快速入门
步骤:
1.导入驱动jar包 mysql-connector-java-8.0.19.jar
复制mysql-connector-java-8.0.19.jar到项目的libs目录下,libs文件可以自己建,也可以不建。然后右键–>Add as Library
2.编写代码注册驱动
3.获取数据库的连接对象Connection
4.定义SQL
5.获取执行SQL语句的对象Statement
6.执行SQL,接受返回结果
7.处理结果
8.释放资源
package com.wcy.demo1.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/**
* JDBC快速入门
*/
public class JdbcDemo1 {
public static void main(String[] args) throws Exception {
//1.导入驱动jar包
//2.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//3.获取数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8", "root", "121017");
//4.定义sql语句
String sql="update account set balance=1000 where id=1";
//5.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//6.执行sql
int count = stmt.executeUpdate(sql);
//7.处理结果
System.out.println(count);
//8.释放资源
stmt.close();
conn.close();
}
}
3.详解各个对象
3.1 DriverManager:驱动管理对象
功能:
1.注册驱动:static void registerDriver(Driver driver) :注册与给定的驱动程序 DriverManager 。
写代码使用:Class.forName(“com.mysql.cj.jdbc.Driver”);
通过查看源码发现在 com.mysql.cj.jdbc.Driver类中存在静态代码块
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
注意:mysql5之后的jar包可以省略注册驱动的步骤。但建议写上!
**2.获取数据库连接:static Connection getConnection(String url, String user, String password) :尝试建立与给定数据库URL的连接。 **
参数:
url:指定连接的路径。语法:jdbc:mysql://IP地址(域名):端口号/数据库名称(注意:驱动jar包如果在8.0以上,则需要这样写:jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8)
细节:如果连接的是本机的sql服务器,并且mysql服务默认是3306,则url可以简写为jdbc:mysql:///数据库名称
user:用户名
password:密码
3.2 Connection:数据库连接对象
功能:
1.获取执行sql的对象
Statement createStatement() :创建一个 Statement对象,用于将SQL语句发送到数据库。
PreparedStatement prepareStatement(String sql)
创建一个 PreparedStatement对象,用于将参数化的SQL语句发送到数据库。
2.管理事务
开启事务:void setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务。
提交事务:void commit()
回滚事务:void rollback()
3.3 Statement:执行SQL的对象
3.3.1 执行Sql
1.boolean execute(String sql) :可以执行任意的sql。
2.int executeUpdate(String sql) :执行给定的SQL语句,这可能是 INSERT , UPDATE ,或 DELETE语句,或者不返回任何内容,如SQL DDL语句的SQL语句。
注意:返回值是影响的行数,可以通过影响行数判断DML语句是否执行成功,返回值大于0的则执行成功,反之则失败
3.ResultSet executeQuery(String sql) :执行给定的SQL语句,该语句返回单个 ResultSet对象。
3.3.2 练习:
1.account表 添加一条记录
package com.wcy.demo1.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* account表 添加一条记录 insert 语句
*/
public class Jdbcdemo2 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.定义sql
String sql="insert into account values(null,'王五',3000)";
//3.获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8", "root", "121017");
//4.获取执行sql对象 Statement
stmt = conn.createStatement();
//5.执行sql
int count = stmt.executeUpdate(sql);//影响的行数
//6.处理结果
System.out.println(count);
if(count>0){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//stmt.close();
//7.释放资源
//避免空指针异常
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
输出结果:


2.account表 修改记录
package com.wcy.demo1.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* account表 修改记录
*/
public class JdbcDemo3 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=GMT", "root", "121017");
//3.定义sql
String sql="update account set balance=200 where id=5";
//4.获取执行sql对象
stmt = conn.createStatement();
//5.执行sql
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
if(count>0){
System.out.println("修改成功!");
}else{
System.out.println("修改失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//stmt.close();
//7.释放资源
//避免空指针异常
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
输出结果:


3.account表 删除一条记录
package com.wcy.demo1.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
* account表 删除一条记录
*/
public class JdbcDemo4 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=GMT", "root", "121017");
//3.定义sql
String sql="delete from account where id=5";
//4.获取执行sql对象
stmt = conn.createStatement();
//5.执行sql
int count = stmt.executeUpdate(sql);
//6.处理结果
System.out.println(count);
if(count>0){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//stmt.close();
//7.释放资源
//避免空指针异常
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
输出结果:


3.4 ResultSet:结果集对象
boolean next();游标向下移动一行,判断当前行是否时最后一行末尾,如果是则返回false,反之返回true。
getxxx(参数);获取数据 xxx代表数据类型 如int getInt(),String getString()
参数:1.int 代表列的编号,从1开始 2.String:代表列的名称
我们先用一下这几个方法,这并不是ResultSet正确使用!!!
package com.wcy.demo1.jdbc;
import java.sql.*;
/**
* account表 删除一条记录
*/
public class JdbcDemo5 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=GMT", "root", "121017");
//3.定义sql
String sql="select * from account";
//4.获取执行sql对象
stmt = conn.createStatement();
//5.执行sql
rs = stmt.executeQuery(sql);
//6.处理结果
//6.1让游标向下移动一行
rs.next();
//6.2获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);//1---zhangsan---1000.0
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//stmt.close();
//7.释放资源
//避免空指针异常
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
注意:上面只是使用以下方法,但这并不是ResultSet的正确用法。如果表中的数据我们并不知道有点多少,重复去使用上述代码查询的话,当数据没有了,此时运行就会出现异常。那么我们应该则么做才可以解决这个问题呢?我们知道next()方法的作用是光标向下移动一行,那我们在向下移动的时候,是不是得先做一个判断,判断下一行到底有没有数据。有数据我就获取,没有数据,我就不获取。所以,我们应该如下使用!
while(rs.next()){
//循环判断游标是否是最后一行末尾。
//获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);//1---zhangsan---1000.0,4---lisi---1500.0
}
3.5 PreparedStatement:执行SQL的对象
详情请看API文档
4.JDBC工具类:JDBCUtils
4.1目的
简化书写
分析:
1.注册驱动也抽取.
2.抽取一个方法获取连接对象.
需求:不想传递参数(麻烦),还得保证工具类的通用性
解决:配置文件
Jdbc.properties
url=…
user=…
password=…
3.抽取一个方法来释放资源
1.首先创建文件jdbc.properties放在src目录下
url=jdbc:mysql:///test?serverTimezone=GMT
user=root
password=121017
driver=com.mysql.cj.jdbc.Driver
2.其次创建JDBCUtils类
package JDBCUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* JDBC工具类
*/
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 文件的读取,只需要读取一次即可拿到这些值,使用静态代码块
*/
static {
//读取资源文件,获取值。
try {
//1.Properties集合类
Properties pro=new Properties();
//获取src路径下的文件的方式---ClassLoader 类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("Jdbc.properties");
//2.加载文件
pro.load(is);
//pro.load(new FileReader("src/jdbc.properties"));
//3.获取属性赋值
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");
//4.注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return 连接对象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* 释放资源
* @param stmt
* @param conn
*/
public static void close(Statement stmt,Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
3.在测试类中使用工具类
package com.wcy.demo1.jdbc;
import JDBCUtils.JDBCUtils;
import java.sql.*;
/**
* account表 删除一条记录
*/
public class JdbcDemo6 {
public static void main(String[] args) {
Statement stmt=null;
Connection conn=null;
ResultSet rs=null;
try {
//1.注册驱动
/*Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=GMT", "root", "121017");*/
conn = JDBCUtils.getConnection();
//3.定义sql
String sql="select * from account";
//4.获取执行sql对象
stmt = conn.createStatement();
//5.执行sql
rs = stmt.executeQuery(sql);
//6.处理结果
//6.1让游标向下移动一行
while(rs.next()){
//循环判断游标是否是最后一行末尾。
//获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);//1---zhangsan---1000.0
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn);
}
}
}
以上可以看出,使用工具类可以提高代码的复用性,简化代码的书写。
本文详细介绍了Java数据库连接(JDBC)的基本概念,包括驱动管理、数据库连接、SQL执行及结果集处理。并通过实例演示了如何使用JDBC进行数据库操作,如插入、更新、删除和查询数据。
864

被折叠的 条评论
为什么被折叠?



