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

相关文章

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

SpringBoot简单整合ElasticSearch实践

《SpringBoot简单整合ElasticSearch实践》Elasticsearch支持结构化和非结构化数据检索,通过索引创建和倒排索引文档,提高搜索效率,它基于Lucene封装,分为索引库、类型... 目录一:ElasticSearch支持对结构化和非结构化的数据进行检索二:ES的核心概念Index:

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

MySQL中between and的基本用法、范围查询示例详解

《MySQL中betweenand的基本用法、范围查询示例详解》BETWEENAND操作符在MySQL中用于选择在两个值之间的数据,包括边界值,它支持数值和日期类型,示例展示了如何使用BETWEEN... 目录一、between and语法二、使用示例2.1、betwphpeen and数值查询2.2、be

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动

JAVA项目swing转javafx语法规则以及示例代码

《JAVA项目swing转javafx语法规则以及示例代码》:本文主要介绍JAVA项目swing转javafx语法规则以及示例代码的相关资料,文中详细讲解了主类继承、窗口创建、布局管理、控件替换、... 目录最常用的“一行换一行”速查表(直接全局替换)实际转换示例(JFramejs → JavaFX)迁移建

Spring Boot Interceptor的原理、配置、顺序控制及与Filter的关键区别对比分析

《SpringBootInterceptor的原理、配置、顺序控制及与Filter的关键区别对比分析》本文主要介绍了SpringBoot中的拦截器(Interceptor)及其与过滤器(Filt... 目录前言一、核心功能二、拦截器的实现2.1 定义自定义拦截器2.2 注册拦截器三、多拦截器的执行顺序四、过