JDBC流ASCII和二进制数据
PreparedStatement对象可以使用输入和输出流来提供参数数据。能够将整个文件放入可以容纳大值的数据库列,例如CLOB和BLOB数据类型。
有以下方法可用于流式传输数据 -
setAsciiStream():此方法用于提供大的ASCII值。setCharacterStream():此方法用于提供较大的UNICODE值。setBinaryStream():此方法用于提供较大的二进制值。
setXXXStream()方法除了参数占位符之外还需要额外的参数和文件大小。此参数通知驱动程序使用流向数据库发送多少数据。
实例
考虑要将XML文件xml_data.xml上传到数据库表中。下面是XML文件的内容 -
<?xml version="1.0"?>
<Employee>
<id>125</id>
<first>Max</first>
<last>Su</last>
<Salary>18000</Salary>
<Dob>18-08-1978</Dob>
<Employee>
将此XML文件保存在要运行此示例的同一目录中。
此示例将在数据库创建一个表:xml_data,然后将文件xml_data.xml上传到此表中。
复制以下示例代码,并保存在文件:StreamingData.java 中,编译并运行如下 -
// Import required packages
import java.sql.*;
import java.io.*;
import java.util.*;
public class StreamingData {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//Create a Statement object and build table
stmt = conn.createStatement();
createXMLTable(stmt);
//Open a FileInputStream
File f = new File("xml_data.xml");
long fileLength = f.length();
FileInputStream fis = new FileInputStream(f);
//Create PreparedStatement and stream data
String SQL = "INSERT INTO XML_Data VALUES (?,?)";
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1,125);
pstmt.setAsciiStream(2,fis,(int)fileLength);
pstmt.execute();
//Close input stream
fis.close();
// Do a query to get the row
SQL = "SELECT Data FROM XML_Data WHERE id=125";
rs = stmt.executeQuery (SQL);
// Get the first row
if (rs.next ()){
//Retrieve data from input stream
InputStream xmlInputStream = rs.getAsciiStream (1);
int c;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (( c = xmlInputStream.read ()) != -1)
bos.write(c);
//Print results
System.out.println(bos.toString());
}
// Clean-up environment
rs.close();
stmt.close();
pstmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(pstmt!=null)
pstmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
public static void createXMLTable(Statement stmt)
throws SQLException{
System.out.println("Creating XML_Data table..." );
//Create SQL Statement
String streamingDataSql = "CREATE TABLE XML_Data " +
"(id INTEGER, Data LONG)";
//Drop table first if it exists.
try{
stmt.executeUpdate("DROP TABLE XML_Data");
}catch(SQLException se){
}// do nothing
//Build table.
stmt.executeUpdate(streamingDataSql);
}//end createXMLTable
}//end JDBCExample
编译上面代码,如下 -
F:\worksp\jdbc>javac -Djava.ext.dirs=F:\worksp\jdbc\libs StreamingData.java
执行上面编译后的代码,得到以下结果 -
F:\worksp\jdbc>java -Djava.ext.dirs=F:\worksp\jdbc\libs StreamingData
Connecting to database...
Thu Jun 01 21:42:00 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Creating XML_Data table...
<?xml version="1.0"?>
<Employee>
<id>125</id>
<first>Max</first>
<last>Su</last>
<Salary>18000</Salary>
<Dob>18-08-1978</Dob>
<Employee>
Goodbye!
F:\worksp\jdbc>
在执行上面语句后,将在数据库:emp下创建一个名称为:xml_data的表,现在查询xml_data表中的数据,如下所示 -
mysql> select * from xml_data;
+-----+-----------------------------------------------------------------------------------------------------------------------------------+
| id | Data |
+-----+-----------------------------------------------------------------------------------------------------------------------------------+
| 125 | <?xml version="1.0"?>
<Employee>
<id>125</id>
<first>Max</first>
<last>Su</last>
<Salary>18000</Salary>
<Dob>18-08-1978</Dob>
<Employee> |
+-----+-----------------------------------------------------------------------------------------------------------------------------------+
1 row in set
mysql>
JDBC流ASCII和二进制数据的更多相关文章
- Mysql中使用JDBC流式查询避免数据量过大导致OOM
一.前言 java 中MySQL JDBC 封装了流式查询操作,通过设置几个参数,就可以避免一次返回数据过大导致 OOM. 二.如何使用 2.1 之前查询 public void selectData ...
- JDBC存储和读取二进制数据
以下JSP文件用common-fileupload组件实现文件上传,并将文件以二进制文件的形式存入数据库 <% if("POST".equalsIgnoreCase(requ ...
- Node.js之使用Buffer类处理二进制数据
Node.js之使用Buffer类处理二进制数据 Buffer类可以在处理TCP流或文件流时处理二进制数据,该类用来创建一个专门存放二进制数据的缓存区. 1. 创建Buffer对象 1.1 直接创建: ...
- Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net
Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码, 1 1.1. 子模式 urlsafe Or url ...
- Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net
Atitit. 二进制数据ascii表示法,与base64编码解码api 设计标准化总结java php c#.net 1. Base64编码,1 1.1. 子模式 urlsafe Or url u ...
- [19/05/07-星期二] JDBC(Java DataBase Connectivity)_CLOB(存储大量的文本数据)与BLOB(存储大量的二进制数据)
一. CLOB(Character Large Object ) – 用于存储大量的文本数据 – 大字段有些特殊,不同数据库处理的方式不一样,大字段的操作常常是以流的方式来处理的.而非一般的字段,一次 ...
- IO流-文本IO\读写二进制数据
文本IO 一.简述 OutputStreamWriter类使用选定的编码方式吧Unicode字符流转换为字节流,InputStreamReader类将包含字节的输入流转为可以产生Unicode字符的读 ...
- 背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据
[源码下载] 背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据 作者:webabcd 介绍背水一战 Windows 10 之 文件系统 读写文本数 ...
- Java JDBC 操作二进制数据、日期时间
二进制数据 mysql提供了四种类型来存储二进制数据: TinyBlob 最多可存储255字节 Blob 最多可存储65KB MediumBlob 最多可存储16MB LongBlob ...
随机推荐
- bitcoin双花
https://en.bitcoin.it/wiki/Irreversible_Transactions https://www.reddit.com/r/Bitcoin/comments/2e7bf ...
- [SQL in Azure] Getting Started with SQL Server in Azure Virtual Machines
This topic provides guidelines on how to sign up for SQL Server on a Azure virtual machine and how t ...
- glob 文件或目录查找
glob模块是最简单的模块之一,内容非常少.用它可以查找符合特定规则的文件或目录(含相对或绝对路径).跟使用windows下的文件搜索差不多. 在python中,glob模块是用来查找匹配的文件的 在 ...
- MVC的项目部署成应用程序或虚拟目录路径的问题
1.js和css的引用出错 a.~/可以取得应用程序目录 b. ./定位到路径,./代表到本目录,../代表父级目录 2.打开页面view a. ./定位到路径 3.img src a. ./定位 ...
- 如何打开chrome中flash debug player
If you’ve installed the latest version of Google Chrome, and you are having a problem debugging your ...
- input type= file 如何更改自定义的样式
input { @include wh(24px,22px);//sass 宽高 @include pa(0,0); //绝对定位 top:0:left:0: opacity: 0; //透明度: o ...
- SqlServer select * into 对应 Oracle语法
创建新表,并插入旧表值 Sql Server select * into new_emp from emp; Oracle create table new_emp as select * from ...
- django后台显示图片 而不是图片地址
修改admin代码 class Ad_CampaingAdmin(admin.ModelAdmin): list_display = ("content","previe ...
- Android开发(十)——像素单位dp、px、pt、sp的比较
dp(dip): device independent pixels(设备独立像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA.HVGA和QVGA 推荐使用这个,不依赖 ...
- C#学习笔记(24)——C#将PPT批量转为JPG(最简单的方法)
说明(2017-8-1 11:15:46): 1. 哈哈,我就说微软肯定有自己的办法,把PPT转成图片. 2. 主要是要引入两个微软自己的程序集,vs里自带直接添加引用,注意一下版本,12.0是off ...