- 浏览: 144057 次
- 来自: ...
文章分类
最新评论
-
nocb:
太感谢了, 我调了2天,始终找不到原因,
DataOutputStream writeBytes(String s) 中文乱码--ZT -
jbeduhai:
发贴能成功吗,我执行的怎么是说没有登录呢,前面登录是正常的,发 ...
ZT---httpclient如何保持session会话模拟登录后的操作 -
chwanga:
很详细啊,廓然开朗,感谢楼主
filter servlet 区别--ZT -
JMS_Exception:
xvm03 写道promzaid 写道.net 还是 java ...
Java的字符流和字节流 -
xvm03:
promzaid 写道.net 还是 java java
Java的字符流和字节流
图片存入数据库;
InputStream photoStream = new FileInputStream(new File("c:\\blog.jpg"));
sql = "INSERT INTO testtable (img) VALUES (?)";
pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, photoStream, (int) file.length());
pstmt.executeUpdate();
大文件操作数据库:插入,更新,取出
插入:
/*
* This class is used to INSERT data into a BLOB datatype column in an Oracle8i database.
* This class has a method called insertBlobData which takes three input parameters:
* 1) The name of the file to be added to the database
* 2) The description of the file to be added to the database
* 3) The physical path to the file, to be added to the database
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class InsertBlob {
public InsertBlob() {
}
public static void main(String[] args) {
InsertBlob insertBlob1 = new InsertBlob();
if(args.length != 3) {
System.out.println("Usage: java InsertBlob FileName FileDescription FilePath");
System.out.println("Example: java InsertBlob myImage.jpg \"File description text comes here.\" \"C:\\\\MyFolder\\\\myImage.jpg\"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that file with the same name and description already exists in the database.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = insertBlob1.insertBlobData(args[0], args[1], args[2]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
insertBlob1 = null;
}
}
}
private static int insertBlobData(final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to see if a file with the same name and description already exists.
*/
query = "SELECT FileId FROM tblBlobDemo WHERE FileName=\'" + fileName + "\' AND FileDescription=\'" + fileDescription + "\' ORDER BY FileId DESC";
rs = stmt.executeQuery(query);
if(!rs.next()) {
/*
* Insert all the data, for the BLOB column we use the function empty_blob(), which creates a locator for the BLOB datatype.
* A locator is an object that ponts to the actual location of the BLOB data in the database. A locator is essential to manipulate BLOB data.
*/
query = "INSERT INTO tblBlobDemo VALUES(seqFileId.NextVal, sysdate, \'" + fileName + "\', empty_blob(), \'" + fileDescription + "\')";
stmt.execute(query);
/*
* Once the locator has been inserted, we retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileName=\'" + fileName + "\' AND FileDescription=\'" + fileDescription +
"\' ORDER BY FileId DESC FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
Top
更新:
/*
* This class is used to UPDATE a BLOB datatype in an Oracle8i database.
* This class has a method called updateBlobData which takes four input parameters:
* 1) The file-id of the file to be updated in the database
* 2) The name of the new file to be added to the database
* 3) The description of the new file to be added to the database
* 4) The physical path to the new file, to be added to the database
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class UpdateBlob {
public UpdateBlob() {
}
public static void main(String[] args) {
UpdateBlob updateBlob1 = new UpdateBlob();
if(args.length != 4) {
System.out.println("Usage: java UpdateBlob FileId NewFileName NewFileDescription NewFilePath");
System.out.println("Example: java UpdateBlob 1 myNewImage.jpg \"New file description text comes here.\" \"C:\\\\MyFolder\\\\myNewImage.jpg\"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement with the FOR UPDATE clause could not find a record.
* 2 ----- Indicates that the FileName and FileDescription columns could not be updated.
* 3 ----- Indicates a SQLException has occurred.
* 4 ----- Indicates a FileNotException has occurred.
* 5 ----- Indicates a some other Exception has occurred.
* 6 ----- Indicates an error has occurred in the finally block.
*/
final int output = updateBlob1.updateBlobData(args[0], args[1], args[2], args[3]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
updateBlob1 = null;
}
}
}
private static int updateBlobData(final String fileId, final String fileName, final String fileDescription, final String filePath) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
String query = null;
try {
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* First execute a query to update the FileName, FileDescription and the FileData columns.
*/
query = "UPDATE tblBlobDemo SET FileName=\'" + fileName + "\', FileDescription=\'" + fileDescription + "\', FileData=empty_blob() WHERE FileId=" + fileId;
final int numberOfRecordsUpdated = stmt.executeUpdate(query);
if(numberOfRecordsUpdated == 1) {
/*
* Updating a BLOB datatype in a database involves replacing an entire BLOB and not modifying it in place.
* Since a locator has already been inserted for the BLOB datatype using the InsertBlob class.
* We retrieve the locator by executing a SELECT statement with the FOR UPDATE clause to manually lock the row.
*/
query = "SELECT FileData FROM tblBlobDemo WHERE FileId=" + fileId + " FOR UPDATE";
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Once a locator has been retrieved we can use it to insert the binary data into the database.
*/
BLOB blob = ((OracleResultSet)rs).getBLOB("FileData");
os = blob.getBinaryOutputStream();
final File f = new File(filePath);
is = new FileInputStream(f);
final byte[] buffer = new byte[blob.getBufferSize()];
int bytesRead = 0;
while((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
blob = null;
}
else {
returnValue = 1;
}
}
else {
returnValue = 2;
}
}
catch(SQLException e) {
returnValue = 3;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 4;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
query = null;
}
catch(Exception e) {
returnValue = 6;
e.printStackTrace();
}
}
return returnValue;
}
}
Top
取出:
/*
* This class is used to select a BLOB datatype from an Oracle8i database onto the file system.
* This class has a method called selectBlobData which takes two input parameters:
* 1) The file-id of the file to be extracted from the database
* 2) The physical path to which the file must be extracted.
*/
/*
* Import the required Java classes
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* Import the required Oracle classes
*/
import oracle.jdbc.driver.OracleDriver;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;
public class SelectBlob {
public SelectBlob() {
}
public static void main(String[] args) {
SelectBlob selectBlob1 = new SelectBlob();
if(args.length != 2) {
System.out.println("Usage: java SelectBlob FileId FilePath");
System.out.println("Example: java SelectBlob 1 \"C:\\\\MyFolder\\\\\"");
}
else {
try {
/*
* The variable output will return one of the following values:
* 0 ----- Indicates success.
* 1 ----- Indicates that the SELECT statement could not find a record.
* 2 ----- Indicates a SQLException has occurred.
* 3 ----- Indicates a FileNotException has occurred.
* 4 ----- Indicates a some other Exception has occurred.
* 5 ----- Indicates an error has occurred in the finally block.
*/
final int output = selectBlob1.selectBlobData(args[0], args[1]);
System.out.println(output);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
selectBlob1 = null;
}
}
}
private static int selectBlobData(final String fileId, final String path) {
/*
* Initialize the necessary parameters
*/
int returnValue = 0;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
BLOB blob = null;
try {
final String query = "SELECT FileName, FileData FROM tblBlobDemo WHERE FileId = " + fileId;
/*
* Register the Oracle driver
*/
DriverManager.registerDriver(new OracleDriver());
/*
* Establish a connection to the Oracle database. I have used the Oracle Thin driver.
* jdbc:oracle:thin@host:port:sid, "user name", "password"
*/
conn = DriverManager.getConnection("jdbc:oracle:thin:@visions-bwckzjd:1521:o8i", "internal", "oracle");
/*
* Set auto commit to false, it helps to speed up things, by default JDBC's auto commit feature is on.
* This means that each SQL statement is commited as it is executed.
*/
conn.setAutoCommit(false);
stmt = conn.createStatement();
/*
* Execute the SELECT statement
*/
rs = stmt.executeQuery(query);
if(rs.next()) {
/*
* Extract the BLOB data to a file on the local file system.
*/
blob = ((OracleResultSet)rs).getBLOB("FileData");
is = blob.getBinaryStream();
final String fileName = rs.getString("FileName");
final String filePath = path + fileName;
os = new FileOutputStream(filePath);
final int bufferSize = blob.getBufferSize();
final byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
else {
returnValue = 1;
}
}
catch(SQLException e) {
returnValue = 2;
e.printStackTrace();
}
catch(FileNotFoundException e) {
returnValue = 3;
e.printStackTrace();
}
catch(Exception e) {
returnValue = 4;
e.printStackTrace();
}
finally {
/*
* Clean up.
*/
try {
if(is != null) {
is.close();
}
if(os != null) {
os.flush();
os.close();
}
if(stmt != null) {
stmt.close();
}
if(rs != null) {
rs.close();
}
if(conn != null) {
conn.commit();
conn.close();
}
is = null;
os = null;
stmt = null;
rs = null;
conn = null;
blob = null;
}
catch(Exception e) {
returnValue = 5;
e.printStackTrace();
}
}
return returnValue;
}
}
发表评论
-
DataOutputStream writeBytes(String s) 中文乱码--ZT
2010-04-21 10:31 29879java 的DataOutputStream 的 writ ... -
java io-- ZT
2010-04-20 09:25 777Java的核心库java.io提供了全面的IO接口,包括:文件 ... -
字节流与字符流的区别收藏
2009-03-03 20:28 1626字节流与字符流主要 ... -
java的IO总结
2009-03-03 20:25 2100知识点一: 四大等级结构 java语言的i/o库 ... -
Java的字符流和字节流
2008-07-31 20:16 6481IO分两种流 字节流 InputStream Output ...
相关推荐
在Java编程中,将文件保存到数据库是一种常见的需求,特别是在处理图像、文档和其他非结构化数据时。这个过程涉及到将文件转换为二进制数据,然后将这些数据存储到数据库的特定字段中,通常是一个BLOB(Binary Large...
在IT领域,保存文件和从数据库导出文件到本地磁盘是常见的操作,尤其是在软件开发中。本主题主要涉及文件操作、数据库交互以及C#编程语言的应用。以下将详细阐述这些知识点。 首先,文件操作是计算机编程的基础。在...
本文将详细探讨如何使用Java解析TXT文件并将其中的数据导入到MySQL数据库中。 首先,我们需要了解的是“建表.sql”文件。这个文件通常包含了创建数据库表的SQL语句,用于定义数据的结构和类型。在本场景下,它可能...
在存储BMP文件到数据库之前,通常需要将其转换为二进制数据或者Base64编码字符串,以便适应数据库的文本或二进制字段。 在Delphi中,可以使用TImage组件加载BMP文件,并利用TMemoryStream类来处理文件的二进制数据...
在IT领域,文件上传到数据库是一项常见的操作,特别是在构建Web应用程序时。本示例中,我们探讨的是如何通过TCP的Socket通信将图片上传至MySQL数据库,同时涉及了基本的IO字符流读写以及数据库的查询与插入操作。...
从给定的文件信息来看,这段内容涉及到的是一个关于上传二进制文件到数据库的应用程序的源代码。这里,我们将详细解析与这个主题相关的几个关键知识点:上传二进制文件的概念、二进制数据在数据库中的存储方式、以及...
"将word文件存到数据库"这一操作通常涉及到文件读取、数据转换以及数据库操作等多个环节。 首先,Word文件本质上是二进制文件,包含了格式信息和内容数据。要将其存入数据库,我们需要先将这个二进制文件的内容读取...
5. **BLOB类型**: 文件通常以二进制大对象(BLOB)的形式存储在数据库中,如SQL Server的`varbinary(max)`或MySQL的`BLOB`类型。这种类型可以存储大量二进制数据,如图片、文档或音频文件。 6. **性能考虑**: 将...
- 无需考虑数据库的空间限制,适合大文件上传。 - 文件访问速度快,用户体验较好。 3. 缺点: - 安全性较低,文件可能被直接访问,需设置合适的权限。 - 文件管理复杂,如需查找或移动文件,需编写额外的代码。...
在讨论如何将文件上传、下载并以二进制流的方式保存到数据库中时,首先需要了解几个关键概念:文件上传、文件下载、二进制流以及数据库操作。 文件上传通常指的是将本地或者网络上的文件通过网络上传到服务器。在...
通常,我们会选择支持二进制大对象(BLOB)的数据库,如MySQL、PostgreSQL或Oracle等,用于存储字节流数据。创建一个表,包含一个BLOB类型的字段,用于存放图片数据。然后,通过SQL语句或者ORM框架(如Hibernate或...
C# VS2019通过 本应用程序 主要是实现 将 图片,word、excel、PDF、image等类型的文件上传至数据库,存储起来,并实现了 从数据库中将存储的文件 读取解析成 原有的文件存放至本地, 主要解决了 多个客户端可以共享...
在IT行业中,将文件保存到数据库是一种常见的数据存储策略,特别是在需要高效检索、备份或安全性较高的场景下。本文将深入探讨“文件保存...学习并理解这些代码可以帮助开发者更好地实现文件数据库存储的完整流程。
数据库中的文件导出工具是用于将存储在数据库中的非结构化或半结构化数据,如文本文件(.TXT)、Microsoft Word文档(.doc)和Excel表格(.xls),提取到本地文件系统的一种实用程序。这样的工具对于数据分析、备份...
这个数据库文件"jxcbook.bak"正是这样一个系统的数据备份,包含了整个进销存流程中的所有关键信息。下面我们将详细探讨进销存数据库的核心内容及其重要性。 1. **进销存的基本概念** 进销存是企业管理中的三个核心...
同时,如果要从数据库中取出Word文件,可以使用类似的步骤,但此时是使用SqlCommand的`ExecuteScalar`或`ExecuteReader`方法获取数据,然后将二进制数据写入到新的文件中。在处理大量数据时,还可以考虑使用存储过程...
3. **性能考虑**:直接将文件存储在数据库中可能会对性能产生一定影响,尤其是在处理大量文件或大文件时。因此,在实际应用中需根据具体情况权衡是否采用这种方法。 4. **安全性**:在处理敏感文件时,应采取适当的...
本项目关注的是如何使用Java来实现读取Microsoft Word文件,并将其中的数据上传到数据库,以此提升数据录入的效率。这一过程涉及到多个技术点,包括文件I/O、Word文档解析、数据库操作以及可能的数据转换。 首先,...
特别是在教育系统、文档管理系统等应用场景中,往往需要支持用户批量上传文件,并将这些文件的相关信息(如文件名、上传时间、上传人等)保存到数据库中以便后续查询和管理。本文将详细介绍如何使用C#在ASP.NET中...
C# 保存文件到数据库字段 attach new BusAttach ; FileInfo fi new FileInfo txtAttach Text Trim ; attach Fix fi Extension Substring 1 ToLower Trim ; FileStream fs fi OpenRead ; byte[] bytes new byte[fs ...