JDBC流ASCII和二進制數據
阿新 • • 發佈:2018-09-08
nvi 編譯 code pri 占位符 -name ces head 程序
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文件保存在要運行此示例的同一目錄中。
此示例將在數據庫創建一個表: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