java 如何保存、读取数据库字段为blob类型的值

java 如何保存、读取javaBean中定义String类型,oracle数据库字段为blob类型的值

这是我的业务逻辑代码
try {
String encoding = "GBK";
File file = new File("E:\workspaceNeuSoft\tomcat7.0.40\logs\localhost.2015-12-07.log");
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding);// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
// System.out.println(lineTxt);
interfaceLog.setFwqIp(ip);
interfaceLog.setJkLog(lineTxt);
interfaceLogService.createInterfaceLog(interfaceLog);
}
read.close();
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}

这个是mybatis中代码


SELECT seq_neu_interfacelog_id.NEXTVAL FROM DUAL


<![CDATA[
INSERT INTO neu_interfacelog DS
(DS.ROW_ID,
DS.CREATE_BY,
DS.CREATE_DATE,
DS.REMARK,
DS.FWQ_IP,
DS.INTERFACELOG
)
VALUES
(#{rowId},
#{createBy},
SYSDATE,
#{remark},
#{fwqIp},
#{jkLog})

    ]]> 
</insert>


现在控制台报异常
015-12-08 15:00:00,620 INFO  org.quartz.plugins.history.LoggingTriggerHistoryPlugin.triggerComplete:432 - Trigger neuSoftWorkPlatform_TRIGGER_GROUP.interfaceLogExpireBean completed firing job neuSoftWorkPlatform_JOB_GROUP.interfaceLogExpire at  15:00:00 12/08/2015 with resulting trigger instruction code: DO NOTHING

org.springframework.jdbc.UncategorizedSQLException:

Error updating database. Cause: java.sql.SQLException: ORA-01465: 无效的十六进制数字

The error may exist in file [E:\workspaceNeuSoft\neuSoftWorkPlatform\neuSoftWorkPlatform-biz\target\classes\mybatis\mappers\interfaceLog\InterfaceLogMapper.xml]

The error may involve com.neusoft.interfaceLog.dao.InterfaceLogDAO.save-Inline

The error occurred while setting parameters

SQL: INSERT INTO neu_interfacelog DS (DS.ROW_ID, DS.CREATE_BY, DS.CREATE_DATE, DS.REMARK, DS.FWQ_IP, DS.INTERFACELOG ) VALUES (?, ?, SYSDATE, ?, ?, ?)

Cause: java.sql.SQLException: ORA-01465: 无效的十六进制数字

; uncategorized SQLException for SQL []; SQL state [72000]; error code [1465]; ORA-01465: 无效的十六进制数字
; nested exception is java.sql.SQLException: ORA-01465: 无效的十六进制数字

at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:71)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365)
at com.sun.proxy.$Proxy27.insert(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:237)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:79)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:40)
at com.sun.proxy.$Proxy86.save(Unknown Source)
at com.neusoft.interfaceLog.service.impl.InterfaceLogServiceImpl.createInterfaceLog(InterfaceLogServiceImpl.java:60)
at com.haier.openplatform.showcase.quartz.InterfaceLogExpireJob.execute(InterfaceLogExpireJob.java:52)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)

Caused by: java.sql.SQLException: ORA-01465: 无效的十六进制数字

at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1168)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3285)
at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3390)
at com.haier.openplatform.jdbc.HOPPraparedStatement$3.run(HOPPraparedStatement.java:183)
at com.haier.openplatform.jdbc.HOPPraparedStatement$3.run(HOPPraparedStatement.java:180)
at com.haier.openplatform.jdbc.HOPPraparedStatement.doProfile(HOPPraparedStatement.java:382)
at com.haier.openplatform.jdbc.HOPPraparedStatement.execute(HOPPraparedStatement.java:180)
at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:41)
at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:66)
at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:45)
at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:108)
at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:75)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:145)
at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:134)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:355)
... 9 more

java中如何接收一个 十六进制的数据 并保存到数据库中,数据库中字段类型longbolb,如何读取

我这里可以提供一个我刚刚使用过的方案,先把需要存储的图片转为base64编码的字符串,再将此字符串转化为byte[],然后就可以在数据库中用blob字段进行存储了。
比如我这里:
byte[] contextBytes = communityPO.getContentTxt().getBytes();
communityPO.setContentTxtBytes(contextBytes);
数据库中就直接存储这个contextBytes就可以了。
对应的mybatis文件中result中可以这样写:
result column="content_txt" typeHandler="org.apache.ibatis.type.BlobTypeHandler" property="contentTxtBytes"

本地图片转base64编码

/**
     * @Description: 将图片转换成base64编码的字符串
     * @param @param imageSrc 文件路径
     * @param @return
     * @return String
     * @throws IOException
     */
    public static String imageToBase64(String imageSrc) throws IOException {
        //判断文件是否存在
        File file=new File(imageSrc);
        if(!file.exists()){
            throw new FileNotFoundException("文件不存在!");
        }
        StringBuilder pictureBuffer = new StringBuilder();
        FileInputStream input=new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //读取文件
        Base64 base64=new Base64();
        byte[] temp = new byte[1024];
        for(int len = input.read(temp); len != -1;len = input.read(temp)){
            out.write(temp, 0, len);
        }
        pictureBuffer.append(new String( base64.encodeBase64Chunked(out.toByteArray())));
        input.close();
        return pictureBuffer.toString();
    }

网络图片url转base64编码

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import sun.misc.BASE64Encoder;
 
 
public class imgToBase64 {
 
    public static void main(String[] args) throws Exception {
        String url="https://pic.imgdb.cn/item/614201662ab3f51d91e492b3.jpg";
        String a = aa.getBase64ByUrl(url);
        System.out.println(a);
    }
 
    /**
     * 根据图片链接转为base64数据
     *
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static String getBase64ByUrl(String imageUrl) throws Exception {
        // new一个URL对象
        URL url = new URL(imageUrl);
        // 打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置请求方式为"GET"
        conn.setRequestMethod("GET");
        // 超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        // 通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        // 得到图片的二进制数据,以二进制封装得到数据,具有通用性
        byte[] data = readInputStream(inStream);
        BASE64Encoder encode = new BASE64Encoder();
        String s = encode.encode(data);
        return s;
    }
 
    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }
 
}
 

再推荐一篇文章,讲了 BLOB 数据类型在实际应用中的意义和作用。这篇带着大家一起实现了一个学校学生花名册的应用。把学生的信息和学生证件照存在同一张表中。

希望对你有所帮助,有帮助的话,点个赞再走吧。