SQL / JDBC中的内联BLOB / BINARY数据类型

时间:2012-02-16 22:37:20

标签: sql jdbc binary blob inline

假设我想避免在JDBC中使用绑定变量并使用“ad-hoc”语句运行SQL,例如:

connection.createStatement().executeQuery("SELECT ...");

是否有任何约定/ JDBC转义语法来内联BLOB数据类型?我知道H2 has this syntax

INSERT INTO lob_table VALUES (X'01FF');

但这不是标准。任何一般解决方案请注意,我对一般方法感兴趣。我知道这可能会变得非常低效。

3 个答案:

答案 0 :(得分:23)

可能没有JDBC转义语法,所以我搜索了一下,发现并成功测试了以下内容:

  • SQL Server,Sybase ASE,Sybase SQL Anywhere

    INSERT INTO lob_table VALUES (0x01FF);
    
  • DB2

    -- Use a blob constructor. This is not needed for VARCHAR FOR BIT DATA types
    INSERT INTO lob_table VALUES (blob(X'01FF'));
    
  • Derby,H2,HSQLDB,Ingres,MySQL,SQLite

    INSERT INTO lob_table VALUES (X'01FF');
    
  • 的Oracle

    -- As mentioned by a_horse_with_no_name, keep in mind the relatively low
    -- limitation of Oracle's VARCHAR types to hold only 4000 bytes!
    INSERT INTO lob_table VALUES (hextoraw('01FF'));
    
  • 的Postgres

    -- There is also hex encoding as of Postgres 9.0
    -- The explicit cast is important, though
    INSERT INTO lob_table VALUES (E'\\001\\377'::bytea);
    

    有关Postgres的十六进制编码

  • 的详细信息,请参阅A.H.'s answer
  • SQL标准

    -- SQL actually defines binary literals as such 
    -- (as implemented by DB2, Derby, H2, HSQLDB, Ingres, MySQL, SQLite):
    <binary string literal> ::=
      X <quote> [ <space>... ] 
      [ { <hexit> [ <space>... ] <hexit> [ <space>... ] }... ] <quote>
    
    <hexit> ::=
      <digit> | A | B | C | D | E | F | a | b | c | d | e | f
    

答案 1 :(得分:3)

我想在Lukas' answer中添加一些PostgreSQL特定内容:

最简单,最简单的解决方案是(至少从PostgreSQL 9.0开始):

insert into lob_table (data) values( E'\\x0102030405FF' )

没有任何演员表(如果该列已经是bytea个)并且在开头只有一个 \\x标记。这是Binary Data Types部分中记录的“十六进制格式”。

关于X'01FF'语法:根据string constant文档,PostgreSQL支持它 - 用于位字符串。似乎没有从bit到bytea的标准转换。

答案 2 :(得分:0)

public String binaryLiteral(Connection con, byte[] bytes) {
    String databaseName = con.getMetaData().getDatabaseProductName();
    String binary = DatatypeConverter.printHexBinary(bytes);
    switch(databaseName) {
        case "Microsoft SQL Server":
        case "ASE": // Sybase
        case "Adaptive Server Enterprise": // Sybase
            return "CONVERT(VARBINARY(MAX), '0x" + binary + "', 1)";
        case "Oracle":
            return "HEXTORAW('" + binary + "')";
        case "PostgreSQL":
            return "E'\\\\x" + binary + "'";
        case "DB2":
            return "blob(X'" + binary + "')";
        default:
            // SQL Standard (Derby, H2, HSQLDB, Ingres, MySQL, SQLite)
            return "X'" + binary + "'";
    }
}