【问题标题】:Simple example of Postgres query in RubyRuby 中 Postgres 查询的简单示例
【发布时间】:2011-06-08 15:46:39
【问题描述】:

在我的一生中,我找不到一个简单的例子来运行类似的东西

"SELECT * FROM MyTable"

在红宝石中。我发现的所有东西都假设是 ORM 或 Rails。现在,我不想要 ORM;我不想要 Rails。我正在寻找使用 pg gem 并执行简单查询的独立程序。

【问题讨论】:

  • 感谢您提出这个问题。我试图通过谷歌搜索找到答案,但我能找到的所有文档显然都假设我已经知道如何使用 ruby​​-pg。

标签: ruby postgresql


【解决方案1】:

来自 pg gem 文档 (http://rubydoc.info/gems/pg/0.10.0/frames)

require 'pg'
conn = PGconn.open(:dbname => 'test')
res  = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
res.getvalue(0,0) # '1'
res[0]['b']       # '2'
res[0]['c']       # nil

我的下一个问题是使用需要密码的数据库进行身份验证。 看起来您可以发送这样的连接字符串:
PGconn.connect( "dbname=test password=mypass") 或使用带参数的构造函数:
PGconn.new(host, port, options, tty, dbname, login, password) 或使用类似:password => '...' 的哈希,请参阅here 了解所有可用选项。

【讨论】:

  • 好简单的例子,谢谢。我通过 psql、python、Java 和 Perl 使用过 PostgreSQL,但从未使用过 Ruby,这使得验证我的 Pg gem 安装是否正常变得很简单。赞赏。
  • 如何在表格中打印这个结果,就像在 pgadmin gui 工具中一样?
【解决方案2】:

试试这个:

require 'pg'

conn = PGconn.connect("ip adddress", 5432, '', '', "db name", "user", "password")
res  = conn.exec('select tablename, tableowner from pg_tables')

res.each do |row|
  puts row['tablename'] + ' | ' + row['tableowner']
end

【讨论】:

  • 看起来这使用了已被 'pg' gem 取代的 'postgres' gem:rubygems.org/gems/postgres
  • 如何在表格中打印这个结果,就像在 pgadmin gui 工具中一样?
  • 我将答案编辑得更清楚一点。你得到了一个哈希数组,所以你可以以任何你喜欢的方式输出它。上面的示例将打印“tablename | owner”的行。
【解决方案3】:

对于 gem pg 的较新版本(例如,0.18.3 到当前最新版本 0.21.0),而不是使用:

conn = PGconn.connect(*args)

(PGconn、PGresult 和 PGError 常量已被弃用,并将被 从 1.0 版开始删除。)

你应该使用conn = PG.connect(*args),例如:

require 'pg'

conn = PG.connect("IP-Address", 5432, '', '', "database-name", "username", "password")
res = conn.exec('select product_id, description, price from product')

res.each do |row|
    puts row
end

参考链接:gem pg

【讨论】:

    【解决方案4】:

    我整理了一个示例,如果您安装了 Docker、ruby 和 pg gem,则可以使用:

    db=pgexample
    
    docker rm -f $db &> /dev/null
    docker run -itd --name $db -p 4242:5432 postgres:10
    
    sleep 3 # wait for postgres to start
    
    docker exec -u postgres $db psql -c "
        CREATE TABLE things (
            id serial PRIMARY KEY,
            name varchar (50) NOT NULL
        );
    
        INSERT INTO things (name) VALUES ('foo');
        INSERT INTO things (name) VALUES ('bar');
        INSERT INTO things (name) VALUES ('baz');
    "
    
    docker exec -u postgres $db psql -c 'SELECT * FROM things;'
    #  id | name
    # ----+------
    #   1 | foo
    #   2 | bar
    #   3 | baz
    # (3 rows)
    
    ruby <<EOF
    require 'pg'
    
    conn = PG.connect(dbname: 'postgres', host: 'localhost', user: 'postgres', port: 4242)
    q = ARGV.first || 'SELECT * FROM things;'
    p conn.exec(q).to_a
    EOF
    # [{"id"=>"1", "name"=>"foo"}, {"id"=>"2", "name"=>"bar"}, {"id"=>"3", "name"=>"baz"}]
    
    docker rm -f $db
    

    【讨论】:

      【解决方案5】:

      在新版本中您需要使用PG::Connection 而不是PGconn

      它是这样工作的:

      require 'pg'
      
      conn = PG::Connection.open(dbname: 'test')
      
      res = conn.exec_params('SELECT $1 AS a, $2 AS b, $3 AS c', [1, 2, nil])
      res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
      

      参见 pg 文档:https://deveiate.org/code/pg/PG/Connection.html

      【讨论】:

        猜你喜欢
        • 2014-10-10
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-08
        • 2011-10-13
        • 2017-09-07
        • 2012-02-05
        相关资源
        最近更新 更多