Last active
June 8, 2020 02:08
-
-
Save euccas/afe1a002d4a2dfb1601c4890bf414bd4 to your computer and use it in GitHub Desktop.
postgresql JSONB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pg' | |
require 'json' | |
def db_connect(host, dbname, user, password) | |
begin | |
conn = PGconn.connect(host, 5436, '', '', dbname, user, password) | |
rescue | |
puts "Failed to connect to database #{dbname} on #{host}" | |
end | |
return conn | |
end | |
# connect vCloud database | |
puts 'Connect to AIR database' | |
db_conn_vcloud = db_connect('dbpgvcloudprd01', 'vcloud', 'rebo', 'rebo') | |
if db_conn_vcloud == nil | |
puts 'Failed to connect to vCloud database' | |
exit(1) | |
end | |
puts '... ok' | |
table_name = 'air_a530_releases' | |
my_hash = Hash.new | |
my_hash[:hlm] = Hash.new | |
my_hash[:hlm] = {:version => '111', :owner => 'euchen'} | |
my_hash[:driver] = Hash.new | |
my_hash[:driver] = {:version => '222', :owner => 'asdf'} | |
new_data = JSON.generate(my_hash) | |
puts new_data | |
new_time = Time.now | |
sql_query =<<-END_SQL_QUERY.gsub(/\s+/, ' ').strip | |
INSERT INTO #{table_name} | |
(delivery_time, data) | |
VALUES (\'#{new_time}\', \'#{new_data}\') | |
END_SQL_QUERY | |
puts "SQL query: #{sql_query}" | |
res = db_conn_vcloud.exec(sql_query) | |
puts "cmd_status: #{res.cmd_status}" | |
sql_query =<<-END_SQL_QUERY.gsub(/\s+/, ' ').strip | |
SELECT data FROM #{table_name} | |
END_SQL_QUERY | |
puts "SQL query: #{sql_query}" | |
res = db_conn_vcloud.exec(sql_query) | |
puts "result" | |
res.each do |r| | |
result_hash = JSON.parse(r['data']) | |
result_hash.each do |k, v| | |
puts "#{k}: #{v}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment