- JDBC概述
- 一、第一个JDBC代码
- 二、获取数据库连接的5种方式
- 三,ResultSet
- PreparedStatement
- 四,JDBCUtils
JDBC概述
1,JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题。
2,Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
一、第一个JDBC代码
package jdbc;
import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class jdbc01 {
public static void main(String[] args) throws SQLException {
//1,注册驱动
Driver driver = new Driver();
//2,得到连接
//(1)jdbc:mysql:// 规定好表示协议,通过jdbc的方式连接mysql
//(2)localhost 主机,可以是IP地址
//(3)3306表示mysql监听的端口
//(4)db01 连接到mysql dbms 的哪个数据库
//(5)mysql的连接本质就是socket连接
String url = "jdbc:mysql://localhost:3306/db01?serverTimezone=UTC";
//将 用户名和密码放入到Properties 对象
Properties properties = new Properties();
//user 和 password 是规定好的,后面的看情况
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
//3,执行SQL
String sql="insert into t_student values (1,'张三','男',21,'2023-9-1','java01班','zs@126.com')";
//statement 用于执行静态SQL语句并返回其生成的结果对象
Statement statement = connect.createStatement();
int rows=statement.executeUpdate(sql);//如果是dml语句,返回的就是影响的行数
System.out.println(rows > 0 ? "成功": "失败");
//4,关闭连接资源
statement.close();
connect.close();
}
}
二、获取数据库连接的5种方式
1,直接使用com.mysql.cj.jdbc.Driver(),属于静态加载,灵活性差,依赖强
2,使用反射加载Driver类,动态加载,更加灵活,减少依赖性
3,使用DriverManager替换Driver进行统一管理
4,使用Class.forName 自动完成注册驱动,简化代码
5,使用配置文件,连接数据库更灵活
代码如下(示例):
package jdbc;
import com.mysql.cj.jdbc.Driver;
import org.junit.Test;
import javax.xml.ws.Action;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
//分析Java连接mysql的5种方式
public class jdbcConn {
@Test//alt+enter导入Junit包
public void connect01() throws SQLException {
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/db01?serverTimezone=UTC";
//将 用户名和密码放入到Properties 对象
Properties properties = new Properties();
//user 和 password 是规定好的,后面的看情况
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
@Test
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver类,动态加载更加灵活,减少依赖性
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/db01?serverTimezone=UTC";
//将 用户名和密码放入到Properties 对象
Properties properties = new Properties();
//user 和 password 是规定好的,后面的看情况
properties.setProperty("user","root");
properties.setProperty("password","123456");
Connection connect = driver.connect(url, properties);
System.out.println("方式2="+connect);
}
//方式3,使用DriverManager 替代 Driver 进行统一管理
@Test
public void connect03() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
//使用反射加载Driver
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/db01?serverTimezone=UTC";
String user = "root";
String password = "123456";
DriverManager.registerDriver(driver);//注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第三种方式"+connection);
}
//方式4,使用Class.forName 自动完成注册驱动,简化代码
//这种方式是使用最多的
@Test
public void connect04() throws ClassNotFoundException, SQLException {
//使用反射加载了Driver类
Class.forName("com.mysql.cj.jdbc.Driver");
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/db01?serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第4种"+connection);
}
@Test
//方式5,在4的基础上改进,使用配置文件,连接数据库更灵活
public void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("方式5"+connection);
}
}
三,ResultSet
1,表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
2,ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
3,next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环来遍历结果集
代码如下(示例):
package jdbc.resultset_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
//演示select语句返回ResultSet,并取出结果
public class ResultSet_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1,注册驱动
Class.forName(driver);
//2,得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3,得到Statement
Statement statement = connection.createStatement();
//4,组织SQL语句
String sql="select sno,sname,sex,age from tb_student";
//执行给定的SQL语句,该语句返回单个 ResultSet对象
ResultSet resultSet = statement.executeQuery(sql);
//5,使用while循环取出数据
while (resultSet.next()){//让光标向后移动,如果没有更多行,则返回false
int sno=resultSet.getInt(1);//获取该行的第一列数据
String sname=resultSet.getNString(2);
String sex=resultSet.getNString(3);
int age=resultSet.getInt(4);
System.out.println(sno+"t"+sname+"t"+sex+"t"+age);
}
//6,关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
PreparedStatement
//1,组织SQL,其中的?就相当于占位符
String sql="select name,pwd from admin where name=? and pwd=?";
//2,preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//3,给?赋值
preparedStatement.setString(1,admin_name);
preparedStatement.setString(2,admin_pwd);
//4,执行select语句的使用 executeQuery
//如果是dml(update,insert,delete)executeupdate()
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
System.out.println("success");
}else{
System.out.println("fail");
}
四,JDBCUtils
package jdbc.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
//这是一个工具类,完成mysql的连接和关闭资源
public class JDBCUtils {
//定义相关属性(4个),因为只需要一份,因此,我们做成static
private static String user;//用户名
private static String password;//密码
private static String url;//url
private static String driver;//驱动名
//在static代码块去初始化
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\mysql.properties"));
//读取相关属性值
user=properties.getProperty("user");
password=properties.getProperty("password");
url=properties.getProperty("url");
driver=properties.getProperty("driver");
} catch (IOException e) {
//在实际开发中,我们可以这样处理
//1,将编译异常转成 运行异常
//2,这时调用者可以选择捕获异常,也可以选择默认处理该异常
throw new RuntimeException(e);
}
}
//连接数据库,返回Connection
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//关闭相关资源
public static void close(ResultSet set, Statement statement,Connection connection){
//判断是否为null
try {
if(set !=null){
set.close();
}
if(statement != null){
statement.close();
}
if(connection !=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package jdbc.utils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtils_Use {
public static void main(String[] args) {
}
public void testSelect(){
//1,得到连接
Connection connection = null;
//2,组织一个sql
String sql="select * from tb_student";
PreparedStatement preparedStatement = null;
ResultSet set=null;
//3,创建一个PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//执行,得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()){
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(set,preparedStatement,connection);
}
}
@Test
public void testDML(){
//1,得到连接
Connection connection = null;
//2,组织一个sql
String sql="update tb_student set sname= ? where sno= ?";
PreparedStatement preparedStatement = null;
//3,创建一个PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1,"李四");
preparedStatement.setString(2,"1");
//执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
}
}



