Ruby PostgreSQL 教程

发布于 2024-11-01 08:50:51 字数 1539 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沙与沫 2024-11-08 08:50:51

请更具体地说明您正在使用的 postgresql 库。

除了 ActiveRecord 之外,我将假设使用“pg”gem。

项目源有一个可能有用的 html 文件。
转到 https://bitbucket.org/ged/ruby-pg /src/b477174160c8/doc/postgres.html
然后点击html右上角的“raw”。在网络浏览器中打开该文件。

此示例代码可帮助您连接(从 html 文件复制):

require "postgres"
conn = PGconn.connect("localhost", 5432, "", "", "test1")
# or: conn = PGconn.open('dbname=test1')
res = conn.exec("select * from a;")

res 对象是 PGResult。向下滚动到 html 中的该部分,查看可以调用哪些方法。

此链接有一个 PGResult 示例:
http://rubydoc.info/gems/pg/0.10.0/PGresult

摘抄:

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

Please be more specific about what postgresql library you're using.

I'm going to assume the 'pg' gem, apart from ActiveRecord.

The project source has an html file that might be helpful.
Go to https://bitbucket.org/ged/ruby-pg/src/b477174160c8/doc/postgres.html
Then click "raw" at the upper right side of the html. Open the file in your web browser.

This sample code helps you connect (copied from the html file):

require "postgres"
conn = PGconn.connect("localhost", 5432, "", "", "test1")
# or: conn = PGconn.open('dbname=test1')
res = conn.exec("select * from a;")

The res object is a PGResult. Scroll down to that section in the html to see what methods you can call.

This link has a PGResult example:
http://rubydoc.info/gems/pg/0.10.0/PGresult

Excerpt:

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
电影里的梦 2024-11-08 08:50:51

我确认,“postgres”软件包已过时,您需要“pg”。

我花了很多时间才得到一个使用 ruby​​ 和 postgres 的基本 select * from movie 。由于我很友善,这是我的代码:

postgres Preparation (database=megatest user=roger pass=123456 table=films)

$ su postgres 
psql 
CREATE USER roger WITH PASSWORD '123456';

GRANT ALL PRIVILEGES ON DATABASE megatest to roger;

megatest=# GRANT SELECT ON films TO PUBLIC;

PG package Preparation

sudo gem install pg

Ruby Code

require 'pg'

conn=PGconn.connect( :hostaddr=>"127.0.0.1", :port=>5432, :dbname=>"megatest", :user=>"roger", :password=>'123456')
# or for a non IP address :host => 'my.host.name.com' instead of hostaddr

# run the query
res = conn.exec("SELECT * FROM films")

# Ran only once in order to get field Name
fieldArray=res.fields()
fieldArray.each do |elem|
    print "elem="+elem+"\n"
end

# print data from the query
res.each{ |row|
    puts "Code="+row["code"]  +" title="+row["title"] +" did="+row["did"] +" date_prod="+row["date_prod"] +" kind="+row["kind"] +" len="+row["len"]
}

Results

root@eblain-VirtualBox:/home/eblain/ruby# ruby postgresTest.rb
Code=UA502 title=Bananas did=105 date_prod=1971-07-13 kind=Comedy len=01:22:00
Code=UA503 title=Cowboy did=105 date_prod=1979-07-13 kind=Horror len=01:32:00
Code=UA544 title=YoBro did=105 date_prod=1981-07-13 kind=Action len=01:42:00

I confirm, "postgres" package is outdated, you need "pg".

It tooks me lot of time just to get a basic select * from films working with ruby and postgres. As I am kind, here is my code:

postgres preparation (database=megatest user=roger pass=123456 table=films)

$ su postgres 
psql 
CREATE USER roger WITH PASSWORD '123456';

GRANT ALL PRIVILEGES ON DATABASE megatest to roger;

megatest=# GRANT SELECT ON films TO PUBLIC;

PG package preparation

sudo gem install pg

Ruby Code

require 'pg'

conn=PGconn.connect( :hostaddr=>"127.0.0.1", :port=>5432, :dbname=>"megatest", :user=>"roger", :password=>'123456')
# or for a non IP address :host => 'my.host.name.com' instead of hostaddr

# run the query
res = conn.exec("SELECT * FROM films")

# Ran only once in order to get field Name
fieldArray=res.fields()
fieldArray.each do |elem|
    print "elem="+elem+"\n"
end

# print data from the query
res.each{ |row|
    puts "Code="+row["code"]  +" title="+row["title"] +" did="+row["did"] +" date_prod="+row["date_prod"] +" kind="+row["kind"] +" len="+row["len"]
}

Results

root@eblain-VirtualBox:/home/eblain/ruby# ruby postgresTest.rb
Code=UA502 title=Bananas did=105 date_prod=1971-07-13 kind=Comedy len=01:22:00
Code=UA503 title=Cowboy did=105 date_prod=1979-07-13 kind=Horror len=01:32:00
Code=UA544 title=YoBro did=105 date_prod=1981-07-13 kind=Action len=01:42:00
痕至 2024-11-08 08:50:51

您只需要需要 pg gem 并建立与数据库的连接:

require 'pg'
# require 'active_record'  # uncomment for not Rails environment

ActiveRecord::Base.establish_connection(:adapter => "postgresql",
                                        :username => "username",
                                        :password => "password",
                                        :database => "database")

当您定义从 ActiveRecord::Base 继承的模型时,它们将使用此数据库连接。其他一切都应该像 Rails 中一样工作。

You only need to require the pg gem and establish the connection to the DB:

require 'pg'
# require 'active_record'  # uncomment for not Rails environment

ActiveRecord::Base.establish_connection(:adapter => "postgresql",
                                        :username => "username",
                                        :password => "password",
                                        :database => "database")

When you define models to inherit from ActiveRecord::Base they will use this database connection. Everything else should work like it does in Rails.

水中月 2024-11-08 08:50:51

对于参数化 SQL 语句,您应该使用 PGconn#exec_params,例如

conn = PGconn.new(:dbname => 'test')
conn.exec_params(
    'INSERT INTO comedians (first_name, last_name) VALUES ($1, $2)',
    ['Louis', 'CK'])
conn.close

来源:http ://deveiate.org/code/pg/PGconn.html

在此处查看可传递给 PGconn 构造函数的参数的完整列表。

For parametrized SQL statements, you should use PGconn#exec_params, e.g.

conn = PGconn.new(:dbname => 'test')
conn.exec_params(
    'INSERT INTO comedians (first_name, last_name) VALUES ($1, $2)',
    ['Louis', 'CK'])
conn.close

Source: http://deveiate.org/code/pg/PGconn.html

Look here for a complete list of parameters that can be passed to the PGconn constructor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文