Ruby/Database/postgres
Материал из Wiki.crossplatform.ru
Create table and insert data in postgres
require "postgres" conn = PGconn.connect("",5432, "", "", "testdb") conn.exec("create table rtest ( number integer default 0 );") conn.exec("insert into rtest values ( 99 )") res = conn.query("select * from rtest") # res id [["99"]]
create the table
require "dbi" DBI.connect("dbi:Pg:rdg", "matz", "123", "AutoCommit" => true) {|dbh| dbh.do "CREATE TABLE Lang ( id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(10) NOT NULL, creator VARCHAR(10) NOT NULL, age INTEGER )" } dbh.do "INSERT INTO Lang VALUES (1, "C", "Dennis", 28)" sql = "INSERT INTO Lang VALUES (?, ?, ?, ?)" dbh.do( sql, 2, "Python", "Guido", 10 ) dbh.do( sql, 3, "Tcl", "John", 12 ) sql = "UPDATE Lang SET age=age+? WHERE age IS NOT NULL" rpc = dbh.do( sql, 1 ) puts "#{ rpc } row(s) updated"