简体   繁体   English

Ruby-创建Postgresql数据库的最佳方法

[英]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? 通过ruby脚本制作简单的Postgresql数据库的最佳方法是什么? Can I use active record for this (not sure if it can be used via a ruby script)? 我可以为此使用活动记录吗(不确定是否可以通过ruby脚本使用它)? 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 . 我同意AlexFranco的观点,您可以使用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.. 但是,当您阅读如何使用pg gem时,您可能会想知道应该连接到哪个数据库。毕竟,如果您还没有数据库,那么您根本不想创建一个数据库。

Turns out there is a master-db called postgres . 原来有一个称为postgres的master-db。 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. 有关创建数据库语句的选项,请参见postgresql文档 More info on how to use the pg gem can be found in the docs . 可以在docs中找到有关如何使用pg gem的更多信息。

I think, you can try with the pg gem, 我认为,您可以尝试使用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 这是您可以找到信息的链接,此示例为https://bitbucket.org/ged/ruby-pg/wiki/Home

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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