插入和恢复BLOB值SubType = Text Field Firebird Java

时间:2012-05-25 15:40:40

标签: java jdbc firebird

我正在建立一个项目,我遇到了一个问题 我在数据库Firebird中创建的Blob字段。 该字段将指的是实地观察,其中 我不想限制用户输入的文本量。

但我有一个问题,不知道如何保存和阅读这个字段。

我正在使用JDBC来使用insert prepareStatement stmt stmt.set ... - 对于blob不知道该怎么做也是 不知道如何转换字段的字符串值

2 个答案:

答案 0 :(得分:1)

您可以使用PreparedStatement.setString()ResultSet.getString(),如果您使用BLOB SUB_TYPE 1(又名BLOB SUB_TYPE TEXT),Firebird驱动程序会将其转换为blob或从blob转换为blob。您需要确保连接字符集与blob字符集相同,否则可能会导致字符集转换不正确。

其他选项是显式创建Clob(使用Connection.createClob())并在语句中设置它,或使用setCharacterStream方法。

答案 1 :(得分:0)

要将字符串转换为blob,我找到了this example

//Convert String to Blob
String data = “hello world”;
java.sql.Blob blob = org.hibernate.Hibernate.createBlob(data.getBytes());

//Convert Blob to String
byte[] bdata = blob.getBytes(1, (int)blob.length());
String data1 = new String(bdata);

查看this example setBlob准备好的陈述。这是一件作品。在他们的示例中,您似乎可以在setBlob

上致电PreparedStatement
java.sql.Blob blob = null;
try {
  conn = getConnection();
  // prepare blob object from an existing binary column
  pstmt = conn.prepareStatement("select photo from my_pictures where id = ?");
  pstmt.setString(1, "0001");
  rs = pstmt.executeQuery();
  rs.next();
  blob = rs.getBlob(1);

  // prepare SQL query for inserting a new row using setBlob()
  String query = "insert into blob_table(id, blob_column) values(?, ?)";
  // begin transaction
  conn.setAutoCommit(false);

  pstmt = conn.prepareStatement(query);
  pstmt.setString(1, "0002");
  pstmt.setBlob(2, blob);

  int rowCount = pstmt.executeUpdate();
  System.out.println("rowCount=" + rowCount);
  // end transaction
  conn.commit();
相关问题