LoginSignup
8
10

More than 3 years have passed since last update.

【備忘録】PythonでPostgreSQLからデータを取得する

Posted at

毎回調べるのが面倒なので書き残しておきます。

import psycopg2


# 任意で変更する
postgre_user_name = "user_name"
postgre_user_password = "user_password"
postgre_server = "server"
postgre_server_port = "server_port"
postgre_database_name = "database_name"
postgre_table_name = "table_name"

conn = psycopg2.connect("postgresql://"
                        + postgre_user_name
                        + ":" 
                        + postgre_user_password
                        + "@"
                        + postgre_server
                        + ":"
                        + postgre_server_port 
                        + "/" 
                        + postgre_database_name)
cur = conn.cursor()
sql_sentence = "select count(*) from " + postgre_table_name + ";"
cur.execute(sql_sentence)
cur.fetchall()

接続先は以下のように変換される

postgresql://user_name:user_password@server:server_port/database_name

sql文は以下のように変換される。

select count(*) from table_name;
8
10
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
8
10