LoginSignup
1
0

More than 5 years have passed since last update.

heroku上のPostgres SQLにデータを挿入する

Last updated at Posted at 2019-02-17

sqllite3のDBにインサート
https://qiita.com/tetsu-sh/items/51e76aa69b45a3c67631

今回は上記記事に関してheroku上のPostgresSQLにデータをINSERTした

正直アクセス先を変更してやることと、sqlite3とPostgresSQLとのシンプルな変更点のみ
で基本は同じ

変更点
・モジュールをsqlite3からPostgres用のpsycopg2にする
・connectの引数においてhost,port,dbname,userを指定する。herokuのダッシュボードのcredientialから見れる。
・プレースホルダーが?から%sになる。

import psycopg2

connection = psycopg2.connect("host= port= dbname= user=")
cursor = connection.cursor()


try:
    cursor.executemany("INSERT INTO table名 VALUES(%s,%s,%s,%s,%s,%s,%s)",ids)
    connection.commit()
#idsはリストの入ったタプル

except psycopg2.Error as e:
    print('psycopg2.Error occurred:', e.args[0])

cursor.execute('SELECT*FROM table名')
res=cursor.fetchall()
print(res)


"""
cursor.execute("SELECT*FROM table名")
for x in cursor.fetchall():
    print(x)
"""

connection.close()

プレースホルダーの違いというところにたどり着くまでが大変だった。
いつも大きな進展となる課題解決法はシンプル

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0