简体   繁体   中英

Ruby - best approach to create a postgresql DB

I am new to ruby. What is the best approach to make a simple postgresql DB via a ruby script? Can I use active record for this (not sure if it can be used via a ruby script)? or there are better alternatives?

I appreciate if you could help me with a ruby code snippet, or redirect me through a link.

Thanks.

I agree with AlexFranco that you can easily achieve that with the pg gem . However, when you read how to use the pg gem you might wonder which database you should connect to.. after all you want don't have a database yet, if you had you wouldn't want to create one..

Turns out there is a master-db called postgres . So here's a minimal working example:

require 'pg'

conn = PG.connect(dbname: 'postgres')
conn.exec("CREATE DATABASE foo")

See the postgresql documentation on options for the create database statement. More info on how to use the pg gem can be found in the docs .

I think, you can try with the pg gem,

#!/usr/bin/env ruby

require 'pg'

# Output a table of current connections to the DB
conn = PG.connect( dbname: 'sales' )
conn.exec( "SELECT * FROM pg_stat_activity" ) do |result|
  puts "     PID | User             | Query"
  result.each do |row|
    puts " %7d | %-16s | %s " %
      row.values_at('procpid', 'usename', 'current_query')
  end
end

Here is the link where you can find information,and this example https://bitbucket.org/ged/ruby-pg/wiki/Home

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM