JDBC API
Java DataBase Connectivity
接口 接收各个数据库的实现类
- 注册驱动‘
Class.forName("com.mysql.jdbc.Driver");//将一个类加载到内存 反射
静态方法 registerDriver
- 获取连接 使用DriverManage
String url="jdbc:mysql://127.0.0.1:3306/数据库?userSSL=false";
127.0.0.1 本机 ip地址 3306 mysql端口号 ? 后面跟的是键值对 参数 userSSL是否禁用警告信息
Connection conn=Connection conn=DriverManager.getConnection(url,user,password);//参数自己设置定义
- 定义sql
String sql ="sql语句";
- 4 获取执行sql语句的对象
statement stmt=conn.createStatement();
- 执行sql
int count=stmt.executeUpdate(sql); //返回受影响的行数 适用增删改
- //释放资源
conn.close;
stmt.close
DriverManager(驱动管理)
-
注册驱动
-
1
Class.forName(
"com.mysql.jdbc.Driver"
);
//获取Driver 类的Class对象
Driver类源码 静态方法registerDriver 注册驱动方法,随着Driver类的加载自动执行
-
-
获取数据库连接
- Connection(返回值) 静态方法getConnection(String url,String username, String password);
- 参数详解
-
-
jdbc:mysql://ip地址(域名):端口号/数据库名称?参数键值对1&参数键值对2…
-
示例:jdbc:mysql://127.0.0.1:3306/db1
-
细节:如果连接的是本机mysql服务器,并且mysql服务默认端口是3306,则url可以简写为:jdbc:mysql:///数据库名称?参数键值对
-
配置 useSSL=false 参数,禁用安全连接方式,解决警告提示
-
-
username:数据库的用户名
-
password:数据库的密码
1 | Connection conn=DriverManager.getConnection(url,user,password); |
Connection(连接对象)
- 获取执行sql语句的对象
- 获取执行sql语句的对象 Statement createStatement();//存在sql语句注入攻击
- 获取预编译的sql语句执行对象,解决了注入攻击 PrepaerStatement PrepareStatement(sql);
- 获取执行存储过程的对象 CallableStatement prepareCall(sql);
例如connection.createStatement();
- 管理事务
-
-
提交事务:commit();
-
回滚事务:rollback();
例如 connecion.setAutoCommit(false);//手动提交事务
Statement(执行者对象)语句 叙述 说明
- 用于执行sql语句,并返回结果
-
-
int executeUpdate(sql);
-
参数:要执行的sql语句
-
返回值:影响的行数。
-
-
-
执行DQL语句
-
ResultSet executeQuery(sql);
-
参数:要执行的sql语句
-
返回值:查询出的结果集
-
12345
// .获取执行sql语句的对象
Statement stmt = conn.createStatement();
// .执行sql语句,并接收结果集
ResultSet rs = stmt.executeQuery(sql);
-
ResultSet(结果集对象)
- 用于封装查询储数据的结果
-
-
xxx getXxx(参数) 获取数据
-
xxx:数据类型;如:int getInt(参数) ; String getString(参数)
-
参数
-
int:列的编号,从1开始
-
-
-
// 获取执行sql语句的对象 Statement stmt = conn.createStatement(); // 执行sql语句,并接收结果集 ResultSet rs = stmt.executeQuery(sql); // 处理结果集 while(rs.next()) { //根据编号获取 // System.out.println(rs.getInt(1) + "," + rs.getString(2) + "," + rs.getInt(3)); //根据列名获取(推荐) System.out.println(rs.getInt("id") + "," + rs.getString("name") + "," + rs.getInt("money")); }
- 使用?号,在sql语句中占位
String sql = "select * from user where id = ? and name = ?"
- 调用成员方法,为?赋值setXxx(参数1,参数2)
-
-
参数1: ?的位置编号,从1 开始
-
参数2: ?的实际数据值
1 2 3 4 5 | String user = "太阳" ; // 获取执行sql语句的预编译对象,对sql语句进行预编译 PreparedStatement pst = conn.prepareStatement(sql); //给占位符?号赋值 pst.setString( 1 ,user); |
连接的url中,拼接上:useServerPrepStmts=true mysql就会进行预编译(检查sql语句的正确性安全性,预编译执行一次)
预编译SQL,性能高,有效防止SQL注入,能将敏感字符转义为文本,如’会被转译为\'之后放入sql语句?号的位置。
提高了性能
在获取PreparedStatement对象时,将sql语句发送给mysql服务器进行检查,编译(这些步骤很耗时),而开启了预编译,预编译 一次形成了一个sql模板,只需要进行一次检查,编译
数据库连接池
-
-
它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个
-
释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏
-
好处
-
资源重用
-
提升系统响应速度
-
避免数据库连接遗漏
-
-
DataSource:官方(SUN) 提供的数据库连接池标准接口,由第三方组织实现此接口。
-
从连接池中获取数据库连接的方法:Connection getConnection();
-
-
Druid(德鲁伊)
-
Druid连接池是阿里巴巴开源的数据库连接池项目
-
功能强大,性能优秀,是Java语言最好的数据库连接池之一
-
-
导入jar包 druid-1.1.12.jar
-
定义配置文件
-
加载配置文件
-
获取数据库连接池对象
-
获取连接
-
执行操作
2.示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /* Druid连接池的使用 */ public class DruidDemo { public static void main(String[] args) throws Exception { //1.导入jar包 //2.编写配置文件 //3.加载配置文件 InputStream is = DruidDemo. class .getClassLoader().getResourceAsStream( "druid.properties" ); Properties prop = new Properties(); prop.load(is); //4.获取数据库连接对象 DataSource ds = DruidDataSourceFactory.createDataSource(prop); Connection conn = ds.getConnection(); //5.编写sql语句 String sql = "SELECT * FROM account" ; //6.获取预编译执行者对象 PreparedStatement pst = conn.prepareStatement(sql); //7.执行sql语句,并接收结果 ResultSet rs = pst.executeQuery(); //8.处理结果 while (rs.next()) { System.out.println(rs.getInt( "id" ) + "," + rs.getString( "name" ) + "," + rs.getInt( "money" )); } //9.释放资源 rs.close(); pst.close(); conn.close(); //注意:不是关闭连接,而是将连接归还连接池中 } } |
druid.properties
1 2 3 4 5 6 7 8 9 10 | driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql: //127.0.0.1:3306/db1?useSSL=false&useServerPrepStmts=true username=root password=root #初始化连接数量 initialSize= 5 # 最大连接数 maxActive= 10 # 最大等待时间 maxWait= 3000 |
JDBC简单练习
封装类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | package com.yang.JDBC.A_D_U_Q_Test; public class Brand { private Integer id; private String brandName; private String companyName; private Integer ordered; private String description; private Integer status; public Brand() { } public Integer getId() { return id; } public void setId(Integer id) { this .id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this .brandName = brandName; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this .companyName = companyName; } public Integer getOrdered() { return ordered; } public void setOrdered(Integer ordered) { this .ordered = ordered; } public String getDescription() { return description; } public void setDescription(String description) { this .description = description; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this .status = status; } @Override public String toString() { return "Brand{" + "id=" + id + ", brandName='" + brandName + '\ '' + ", companyName='" + companyName + '\ '' + ", ordered=" + ordered + ", description='" + description + '\ '' + ", status=" + status + '}' ; } } |
查询所有 SelecAll
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | package com.yang.JDBC.A_D_U_Q_Test; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.Test; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Properties; public class SelectAll { @Test public void Test() throws Exception { //通过本类的Class对象获取druid.properties的路径 InputStream resourceAsStream = SelectAll. class .getClassLoader().getResourceAsStream( "druid.properties" ); Properties prop= new Properties(); //获得.properties的内容 prop.load(resourceAsStream); //获得连接池对象 DataSource dataSource = DruidDataSourceFactory.createDataSource(prop); //通过连接池获得连接对象 Connection connection = dataSource.getConnection(); //设置sql语句 String sql= "select * from tb_brand" ; //获得PreparedStatement对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); //获得结果集对象 ResultSet resultSet = preparedStatement.executeQuery(); //设置集合Arrlist ArrayList<Brand> arrayList= new ArrayList<>(); while (resultSet.next()){ Integer id = resultSet.getInt( 1 ); String brandName = resultSet.getString( 2 ); String companyName = resultSet.getString( 3 ); Integer ordered = resultSet.getInt( 4 ); String description = resultSet.getString( 5 ); Integer status = resultSet.getInt( 6 ); //将数据封装为brand对象 Brand brand= new Brand(); brand.setId(id); brand.setBrandName(brandName); brand.setCompanyName(companyName); brand.setOrdered(ordered); brand.setDescription(description); brand.setStatus(status); //将brand对象,添加到List集合中 arrayList.add(brand); } //释放资源 resultSet.close(); preparedStatement.close(); connection.close(); for (Brand brand : arrayList) { System.out.println(brand); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | package com.yang.JDBC.A_D_U_Q_Test; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.Test; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties; public class AddOne { @Test public void Test() throws Exception { //通过本类的字节码对象获得druid.properties内容的字节码 InputStream inputStream = AddOne. class .getClassLoader().getResourceAsStream( "druid.properties" ); //通过MAP集合的子类Propertis中的load方法获得键值对内容 Properties properties = new Properties(); properties.load(inputStream); //将properties获得键值对的值当作参数传入Durid数据连接池 DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); //在连接池中过的连接对象 Connection connection = dataSource.getConnection(); //编写SQL语句 String sql= "insert into tb_brand(id,brand_name,company_name,ordered,description,status) values(?,?,?,?,?,?)" ; //通过连接对象Connection获取预编以sql语句对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); //为占位符?设置参数 String brand_name = "橘子" ; String company_name = "橘子公司" ; Integer ordered = 1 ; String description = "橘子公司制作最好的铁橘子" ; Integer status = 1 ; preparedStatement.setString( 1 , null ); preparedStatement.setString( 2 ,brand_name); preparedStatement.setString( 3 ,company_name); preparedStatement.setInt( 4 ,ordered); preparedStatement.setString( 5 ,description ); preparedStatement.setInt( 6 ,status); //获得结果集对象 返回的是影响条数 int i = preparedStatement.executeUpdate(); if (i> 0 ){ System.out.println( "添加成功" ); } else { System.out.println( "添加失败" ); } //释放资源 preparedStatement.close(); connection.close(); } } |
修改数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package com.yang.JDBC.A_D_U_Q_Test; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.Test; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties; public class Update { @Test public void Test() throws Exception { //通过本类的字节码对象获得druid.properties路径封装进字节输出流中 InputStream inputStream = Update. class .getClassLoader().getResourceAsStream( "druid.properties" ); //创建Propertis map集合对象,获得配置文件中的键值对内容 Properties properties = new Properties(); properties.load(inputStream); //将配置文件中的值当作参数传入Druis数据库连接池当作参数 DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); //通过数据库连接池获取连接对象 Connection connection = dataSource.getConnection(); //编写sql语句 String sql= "update tb_brand set brand_name=?,company_name=?,ordered=?,description=?,status=? WHERE id=?" ; //通过连接对象获得预编译sql语句对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); //为占位符?号赋值 preparedStatement.setString( 1 , new String( "苹果" )); preparedStatement.setString( 2 , new String( "苹果公司" )); preparedStatement.setInt( 3 , new Integer( 1 )); preparedStatement.setString( 4 , new String( "苹果公司制作落地最快的苹果" )); preparedStatement.setInt( 5 , new Integer( 1 )); preparedStatement.setInt( 6 , new Integer( 4 )); //执行结果,返回是影响条数 int i = preparedStatement.executeUpdate(); //释放资源 preparedStatement.close(); connection.close(); //这里只是为了展示执行结果 if (i> 0 ){ System.out.println( "执行成功" ); } else { System.out.println( "执行失败" ); } } } |
删除数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package com.yang.JDBC.A_D_U_Q_Test; import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.Test; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.Properties; public class Delete { @Test public void Test() throws Exception { //通过本类的字节码对象获取druid.propertie配置文件对象 InputStream resourceAsStream = Delete. class .getClassLoader().getResourceAsStream( "druid.properties" ); //通过map集合 properties对象获取配置文件中的键值对内容 Properties properties = new Properties(); properties.load(resourceAsStream); //将配置文件中的键值对的值传入druid数据库连接池当作参数 DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); //从druid数据库连接池获取数据库连接对象 Connection connection = dataSource.getConnection(); //创建sql语句 String sql= "delete from tb_brand where id=?" ; //用数据库连接对象获取预编译sql对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); //为占位符?赋值 preparedStatement.setInt( 1 , 1 ); //执行sql语句,并获得影响条数 int i = preparedStatement.executeUpdate(); //释放资源 preparedStatement.close(); connection.close(); //这里只是为了更好理解 if (i> 0 ){ System.out.println( "执行成功" ); } else { System.out.println( "执行失败" ); } } } |
配置文件 durid.properties
1 2 3 4 5 6 7 8 9 10 | driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql: //127.0.0.1:3306/db2?useSSL=false&useServerPrepStmts=true username=root password=root #初始化连接数量 initialSize= 5 # 最大连接数 maxActive= 10 # 最大等待时间 maxWait= 3000 |