使用预准备语句setcharacterstream h2数据库时输入null

时间:2014-02-15 10:49:16

标签: jdbc prepared-statement h2 clob

我正在尝试使用preparedstatement.setcharacterstream(arg,reader)在h2网站上为clob添加值在数据库中插入空值

Connection con=getConnection();
    pstmnt=con.prepareStatement(sql);
    int paramcounter=1;
    for (Object object : param) {
        if(paramcounter==1) {
            int len=object.toString().length();
            Reader rdr=new StringReader(object.toString());
            pstmnt.setCharacterStream(1, rdr,len);; 
        }
        else{
            pstmnt.setObject(paramcounter, object);
        }           
        paramcounter++;
    }       
    int retvalue=pstmnt.executeUpdate();
    closeConnection();

1 个答案:

答案 0 :(得分:1)

我们没有足够的信息来清楚地说明您可能遇到困难的原因,但以下代码对我有用:

package h2test;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;

public class H2testMain {

    public static void main(String[] args) {
        Connection con = null;
        try {
            // create an in-memory database ("...mem:...")
            con = DriverManager.getConnection("jdbc:h2:mem:");
            Statement s = null;
            try {
                s = con.createStatement();
                s.execute("CREATE TABLE Table1 (Column1 CLOB)");

                InputStream is = new FileInputStream("C:/__tmp/MIME/stuff.txt");
                Reader rdr = new InputStreamReader(is, StandardCharsets.ISO_8859_1);

                PreparedStatement ps = con.prepareStatement(
                        "INSERT INTO Table1 (Column1) VALUES (?)");
                ps.setCharacterStream(1, rdr);
                ps.executeUpdate();

                ResultSet rs = s.executeQuery(
                        "SELECT Column1 FROM Table1");
                int rowNumber = 0;
                while (rs.next()) {
                    String str = rs.getString("Column1");
                    System.out.println(
                            String.format(
                                    "Row %d: CLOB is %d character(s) long.", 
                                    ++rowNumber, 
                                    str.length()));
                }
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

它读取文本文件

02/15/2014  10:55           358,785 stuff.txt

将文件内容写入H2数据库中的CLOB列,从数据库中读取数据,并生成以下控制台输出:

Row 1: CLOB is 358785 character(s) long.