Inserting text string with hex into PostgreSQL as a bytea

前端 未结 5 2009
抹茶落季
抹茶落季 2020-12-13 05:50

I have a text file with several strings of hex in it:

013d7d16d7ad4fefb61bd95b765c8ceb
007687fc64b746569616414b78c81ef1

I would like to sto

5条回答
  •  星月不相逢
    2020-12-13 06:16

    The Ruby Way

    I recently needed to read/write binary data from/to Postgres, but via Ruby. Here's how I did it using the Pg library.

    Although not strictly Postgres-specific, I thought I'd include this Ruby-centric answer for reference.

    Postgres DB Setup

    require 'pg'
    DB = PG::Connection.new(host: 'localhost', dbname:'test')
    DB.exec "CREATE TABLE mytable (testcol BYTEA)"
    BINARY = 1
    

    Insert Binary Data

    sql = "INSERT INTO mytable (testcol) VALUES ($1)"
    param = {value: binary_data, format: BINARY}
    DB.exec_params(sql, [param]) {|res| res.cmd_tuples == 1 }
    

    Select Binary Data

    sql = "SELECT testcol FROM mytable LIMIT 1"
    DB.exec_params(sql, [], BINARY) {|res| res.getvalue(0,0) }
    

提交回复
热议问题