0

I have a quite simple Sinatra application for which I don't want to bother to create a model. I need to insert data into a Postgresql database without a model and, perhaps if possible, without ActiveRecord and also via only pure Sql. I've not found any examples of such a matter. How can I do that then?

Dorion
  • 77
  • 1
  • 1
  • 6
  • 1
    Please read "[ask]" including the linked pages, "[mcve]" and "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)". We'd like to see evidence of your effort. What did you try? Did you search and not find anything? Did you find stuff but it didn't help? Did you try writing code? If not, why? If so, what is the smallest code example that shows what you tried and why didn't it work? Without that it looks like you didn't try and want us to write it for you. – the Tin Man Apr 10 '17 at 19:29

1 Answers1

2

You can use pg gem directly.

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])
# Equivalent to:
#  res  = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')

For specify more connection options check it out the PG::Connection constructor documentation.

NickGnd
  • 5,107
  • 1
  • 20
  • 26
  • I have database.yml. Should I just read it as an ordinary yml file and pass the parameters to ` PG::Connection.open`? Or is there an easier way? – Dorion Apr 10 '17 at 15:31
  • @Dorion yep, I have to read the `yaml` file, take a look to this answer on SO http://stackoverflow.com/questions/3877004/how-do-i-parse-a-yaml-file – NickGnd Apr 10 '17 at 18:10
  • Using the pg gem is one way, but it's very low-level these days. ActiveRecord, Sequel and DataMapper are all Ruby ORM gems that make it easy to talk to a DBM in a more flexible way that is DBM independent and easily portable. They'll also generate excellent SQL, often avoiding inefficient code that inexperienced SQL coders don't know about. I personally prefer Sequel. The author is very experienced with Postgres and always writes for that DBM first. – the Tin Man Apr 10 '17 at 19:32