JDBC(Java Data Base Connectivity)高级用法

2023-11-02 18:58

本文主要是介绍JDBC(Java Data Base Connectivity)高级用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、批处理
Batch
对于大量的批处理,建议使用statement,因为PreparedStatement的预编译空间有限,当数据量特别大时,会发生异常。

示例

package com.lgd.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;/*** 批处理* @author liguodong*/public class Demo05 {public static void main(String[] args) {Connection connection = null;Statement  statement = null;ResultSet rs1 = null;try {//1、加载驱动类Class.forName("com.mysql.jdbc.Driver");//2、建立与数据库的连接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");connection.setAutoCommit(false);//设置为手动提交           statement = connection.createStatement();           long start = System.currentTimeMillis();for(int i=0;i<20000;i++){statement.addBatch("insert into user(username,pwd,regTime) values ('神舟"+i+"号',666666,NOW())");}           statement.executeBatch();           connection.commit();//提交事务          long end = System.currentTimeMillis();          System.out.println("批量插入数据耗时(毫秒):"+(end-start));} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{//执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(rs1!=null){try {rs1.close();} catch (SQLException e) {e.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {e.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}}
}

运行结果:

二、事务
(一)事务基本概念
一组要么同时执行成功,要么同时执行失败的SQL语句,是数据库操
作的一个执行单元!

事务开始于:
连接到数据库上,并执行一条DML语句(INSERT、UPDATE或DELETE)。
前一个事务结束后,又输入了另外一条DML语句。

事务结束于:
执行COMMIT或ROLLBACK语句。
执行一条DDL语句,例如CREATE TABLE语句;在这种情况下,会自动执行COMMIT语句。
执行一条DCL语句,例如GRANT语句;在这种情况下,会自动执行COMMIT语句。
断开与数据库的连接。
执行了一条DML语句,该语句却失败了;在这种情况中,会为这个无效的DML语句执行ROLLBACK语句

事务的四大特点(ACID)
atomicity(原子性)
表示一个事务内的所有操作是一个整体,要么全部成功,要么全部失败。

consistency(一致性)
表示一个事务内有一个操作失败时,所有的更改过的数据都必须回滚到修改前的状态。

isolation(隔离性)
事务查看数据时数据所处的状态,要么是另一并发事务修改它之前的状态,要么是另一事务修改它之后的状态,事务不会查看中间状态的数据。

durability(持久性)
持久性事务完成之后,它对于系统的影响是永久性的。

事务隔离级别由低到高
读取未提交(Read Uncommitted)
读取已提交(Read Committed) (默认)
可重复读(Repeatable Read)
序列化(serializable)

示例:

package com.lgd.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;/*** 事务的用法* @author liguodong**/public class Demo07 {@SuppressWarnings("null")public static void main(String[] args) {Connection connection = null;PreparedStatement  statement1 = null;PreparedStatement  statement2 = null;try {//1、加载驱动类Class.forName("com.mysql.jdbc.Driver");//2、建立与数据库的连接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");connection.setAutoCommit(false);//JDBC中默认自动提交事务,默认是tureString sql1 = "insert into user (username,pwd) values(?,?)";statement1 = connection.prepareStatement(sql1);statement1.setObject(1, "卡特琳娜");statement1.setObject(2, "666");System.out.println("插入一条记录");try {Thread.sleep(6000);} catch (InterruptedException e) {e.printStackTrace();}String sql2 = "insert into user (username,pwd) values(?,?,?)";statement2 = connection.prepareStatement(sql2);statement2.setObject(1, "提莫快跑");statement2.setObject(2, "666");     statement2.executeUpdate();System.out.println("插入另外一条记录");connection.commit();//提交事务} catch (ClassNotFoundException e) {e.printStackTrace();try {connection.rollback(); //回滚操作} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} catch (SQLException e) {e.printStackTrace();}finally{//执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(statement2!=null){try {statement2.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(statement1!=null){try {statement1.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
}

运行结果:
会报SQL异常,并执行回滚操作,因此一条数据也不会插入到数据库中。

三、时间类型
java.util.Date
子类:java.sql.Date 表示年月日
子类:java.sql.Time 表示时分秒
子类:java.sql.Timestamp 表示年月日时分秒

日期比较处理
插入随机日期
取出指定日期范围的记录

示例

package com.lgd.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;/*** 时间处理(java.sql.Date, java.sql.Time, java.sql.Timestamp)* @author liguodong**/public class Demo08 {public static void main(String[] args) {Connection connection = null;PreparedStatement  statement = null;Statement rs1 = null;try {//1、加载驱动类Class.forName("com.mysql.jdbc.Driver");//2、建立与数据库的连接connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");//3、测试PreparedStatement的基本用法   ?占位符String sql1 = "insert into user(username,pwd,regTime,lastLoginTime) values(?,?,?,?)";statement = connection.prepareStatement(sql1);statement.setObject(1, "模特");statement.setObject(2, "mm");//java.sql.Date没有空构造器,必须要传值。java.sql.Date date = new java.sql.Date(System.currentTimeMillis());//如果需要指定日期,可以使用Calendar,DateFormatjava.sql.Timestamp stamp = new java.sql.Timestamp(System.currentTimeMillis());statement.setObject(3, date);statement.setTimestamp(4, stamp);statement.executeUpdate();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{//执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(rs1!=null){try {rs1.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
}

运行结果:

package com.lgd.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;/*** 产生随机时间* @author liguodong**/public class Demo09 {public static void main(String[] args) {Connection connection = null;PreparedStatement  statement = null;Statement rs1 = null;try {Class.forName("com.mysql.jdbc.Driver");connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");for(int i=0; i<1000; i++){String sql1 = "insert into user(username,pwd,regTime,lastLoginTime) values(?,?,?,?)";statement = connection.prepareStatement(sql1);statement.setObject(1, "模特"+i);statement.setObject(2, "mm");//产生随机数int   rand = 1000000+new Random().nextInt(100000000);//java.sql.Date没有空构造器,必须要传值。java.sql.Date date = new java.sql.Date(System.currentTimeMillis()-rand);//如果需要指定日期,可以使用Calendar,DateFormatjava.sql.Timestamp stamp = new java.sql.Timestamp(System.currentTimeMillis()-rand);             statement.setObject(3, date);               statement.setTimestamp(4, stamp);statement.executeUpdate();}   } catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{           //执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(rs1!=null){try {rs1.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
}

运行结果:

package com.lgd.jdbc;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;/*** 时间处理,取出指定时间段的数据* @author liguodong*/public class Demo09 {public static void main(String[] args) {Connection connection = null;PreparedStatement  statement = null;ResultSet rs1 = null;try {Class.forName("com.mysql.jdbc.Driver");connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");            statement = connection.prepareStatement("select * from user where lastLoginTime>? and lastLoginTime<? order by lastLoginTime");java.sql.Timestamp startDate = new java.sql.Timestamp(strDate("2015-5-4 20:30:30"));java.sql.Timestamp endDate = new java.sql.Timestamp(strDate("2015-5-4 21:0:30"));System.out.println(startDate+"--"+endDate);statement.setObject(1, startDate);statement.setObject(2, endDate);rs1 = statement.executeQuery();while (rs1.next()) {//取的时候既可以用索引,还可以用名字。System.out.println(rs1.getInt("id")+"---"+rs1.getString("username")+"---"+rs1.getDate("regTime")+"---"+rs1.getTimestamp("lastLoginTime"));  //System.out.println(rs1.getInt(1)+"---"+rs1.getString(2)+"---"+rs1.getDate(4)+"---"+rs1.getTimestamp(5));}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}finally{//执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(rs1!=null){try {rs1.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(statement!=null){try {statement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}/*** 将字符串代表的日期转化为long数字(格式:yyyy-MM-dd hh:mm:ss)* @param dateString* @return*/public static long strDate(String dateString){DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");try {return format.parse(dateString).getTime();} catch (ParseException e) {e.printStackTrace();return 0;}}   
}

运行结果:
2015-05-04 20:30:30.0–2015-05-04 21:00:30.0
1886—模特882—2015-05-04—2015-05-04 20:31:07.0
1123—模特119—2015-05-04—2015-05-04 20:32:23.0
1048—模特44—2015-05-04—2015-05-04 20:40:20.0
1115—模特111—2015-05-04—2015-05-04 20:41:41.0
1300—模特296—2015-05-04—2015-05-04 20:43:28.0
1011—模特7—2015-05-04—2015-05-04 20:52:44.0
1716—模特712—2015-05-04—2015-05-04 20:53:39.0
1388—模特384—2015-05-04—2015-05-04 20:59:33.0

四、CLOB(Character Large Object)
用于存储大量的文本数据
大字段有些特殊,不同数据库处理的方式不一样,大字段的操作常常是以流的方式来处理的。而非一般的字段,一次即可读出数据。

Mysql中相关类型:
TINYTEXT最大长度为255(2^8-1)字符的TEXT列。
TEXT[(M)]最大长度为65535(2^16-1)字符的TEXT列。
MEDIUMTEXT最大长度为16777215(2^24一1)字符的TEXT列。
LONGTEXT最大长度为4294967295或4GB(2^32一1)字符的TEXT列。

示例

package com.lgd.jdbc;import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** CLOB文本大对象的使用* 包含:将字符集、字符串内容插入到数据库的CLOB字段、将CLOB字段值取出来* @author liguodong**/public class Demo10 {public static void main(String[] args) {Connection conn = null;PreparedStatement  ps = null;ResultSet rs = null;Reader reader = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");          /输入/////ps = conn.prepareStatement("insert into user(username,myInfo) values(?,?)");/*ps.setString(1, "风城玫瑰");//将文本文件字节输入到数据库中ps.setClob(2, new FileReader(new File("d:/rose.txt")));     ps.executeUpdate();ps.setString(1, "风城玫瑰");//将程序中的字符串输入到数据库的CLOB字段中ps.setClob(2, new BufferedReader(new InputStreamReader(new ByteArrayInputStream("司职控球后卫,最年轻的MVP".getBytes()))));ps.executeUpdate();*//导出///          ps = conn.prepareStatement("select * from user where id=?");ps.setObject(1, 2006);rs = ps.executeQuery();while(rs.next()){java.sql.Clob clob = rs.getClob("myInfo");reader = clob.getCharacterStream();int temp=0;while((temp=reader.read())!=-1){System.out.print((char)temp);}}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(reader!=null){try {reader.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}//执行顺序resultset-->statement-->connection这样的关闭顺序!一定要将三个try-catch块分开写!if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(conn!=null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}

运行结果:

五、BLOB(Binary Large Object)
用于存储大量的二进制数据
大字段有些特殊,不同数据库处理的方式不一样,大字段的操作常常是以流的方式来处理的。而非一般的字段,一次即可读出数据。
Mysql中相关类型:
一TINYBLOB最大长度为255(2^8-1)字节的BLOB列。
一BLOB[(M)]最大长度为65535(2^16-1)字节的BLOB列。
一MEDIUMBLOB最大长度为16777215(2^24-1)字节的BLOB列。
一LONGBLOB最大长度为4294967295或4GB(2^32-1)字节的BLOB列。

示例

package com.lgd.jdbc;import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** BLOB文本大对象的使用* 包含:将字符集、字符串内容插入到数据库的CLOB字段、将CLOB字段值取出来* @author liguodong**/public class Demo11 {public static void main(String[] args) {Connection conn = null;PreparedStatement  ps = null;ResultSet rs = null;InputStream is = null;OutputStream os = null;try {Class.forName("com.mysql.jdbc.Driver");conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","liguodong");          /输入////*ps = conn.prepareStatement("insert into userblob (username,headImg) values (?,?) ");ps.setString(1, "sunshine");//将图片输入到数据库中//方式一ps.setBlob(2,new FileInputStream(new File("d:/sunshine.png")));ps.execute();//方式二FileInputStream fis = new FileInputStream("d:/sunshine.png");ps.setBinaryStream(2, fis,fis.available());ps.execute();*//导出///          ps = conn.prepareStatement("select * from userblob where id=?");ps.setObject(1, 1);rs = ps.executeQuery();while(rs.next()){java.sql.Blob blob = rs.getBlob("headImg");is = blob.getBinaryStream();os = new FileOutputStream("d:/coco.png");int temp=0;while((temp=is.read())!=-1){//System.out.print((char)temp);os.write(temp);}           }           } catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{          if(os!=null){try {os.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(is!=null){try {is.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(rs!=null){try {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(conn!=null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}

运行结果:

这篇关于JDBC(Java Data Base Connectivity)高级用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/332611

相关文章

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Java controller接口出入参时间序列化转换操作方法(两种)

《Javacontroller接口出入参时间序列化转换操作方法(两种)》:本文主要介绍Javacontroller接口出入参时间序列化转换操作方法,本文给大家列举两种简单方法,感兴趣的朋友一起看... 目录方式一、使用注解方式二、统一配置场景:在controller编写的接口,在前后端交互过程中一般都会涉及

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.

Maven中引入 springboot 相关依赖的方式(最新推荐)

《Maven中引入springboot相关依赖的方式(最新推荐)》:本文主要介绍Maven中引入springboot相关依赖的方式(最新推荐),本文给大家介绍的非常详细,对大家的学习或工作具有... 目录Maven中引入 springboot 相关依赖的方式1. 不使用版本管理(不推荐)2、使用版本管理(推

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环