pythonpostgresql
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
pythonpostgresql [2021/11/29 14:33] – z0hpvk | pythonpostgresql [2025/03/08 22:24] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 3: | Line 3: | ||
[[https:// | [[https:// | ||
+ | === Connecting to PostgreSQL === | ||
<code python> | <code python> | ||
import psycopg2 | import psycopg2 | ||
+ | import psycopg2.extras | ||
conn = psycopg2.connect(database=" | conn = psycopg2.connect(database=" | ||
print " | print " | ||
- | cur = conn.cursor() | + | #cur = conn.cursor() |
+ | cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) | ||
query = " | query = " | ||
cur.execute(query) | cur.execute(query) | ||
- | for row in cur: | + | rows = cur.fetchall() |
+ | |||
+ | for row in rows: | ||
print(row) | print(row) | ||
+ | print(f" | ||
| | ||
cur.close() | cur.close() | ||
</ | </ | ||
+ | |||
+ | === Example Connection Files === | ||
+ | == Using Config Parser == | ||
+ | <code python> | ||
+ | # database.ini | ||
+ | [postgresql] | ||
+ | host=localhost | ||
+ | database=doob | ||
+ | user=ian | ||
+ | password=pwd | ||
+ | </ | ||
+ | <code python> | ||
+ | # | ||
+ | from configparser import ConfigParser | ||
+ | |||
+ | def config(filename=' | ||
+ | parser = ConfigParser() | ||
+ | parser.read(filename) | ||
+ | params = parser.items(section) | ||
+ | for param in params: | ||
+ | db[param[0]] = param[1] | ||
+ | | ||
+ | return db | ||
+ | </ | ||
+ | |||
+ | <code python> | ||
+ | # | ||
+ | from config import config | ||
+ | |||
+ | def connect() | ||
+ | conn = None | ||
+ | try: | ||
+ | params = config() | ||
+ | conn = psycopg2.connect(**params) | ||
+ | cur = conn.cursor() | ||
+ | cur.execute(' | ||
+ | db_version = cur.fetchone() | ||
+ | print(db_version) | ||
+ | cur.close() | ||
+ | except (Exception, psycopg2.DatabaseError) as error: | ||
+ | print(error) | ||
+ | </ | ||
+ | |||
+ | == Using Credential File == | ||
+ | <code python> | ||
+ | # conndetails.py | ||
+ | PGHOST=" | ||
+ | PGDATABASE=" | ||
+ | PGUSER=" | ||
+ | PGPASSWORD=" | ||
+ | </ | ||
+ | |||
+ | <code python> | ||
+ | import psycopg2 | ||
+ | import conndetails as creds | ||
+ | |||
+ | conn_string = " | ||
+ | + creds.PGUSER +" password=" | ||
+ | conn = psycopg2.connect(conn_string) | ||
+ | |||
+ | cur = conn.cursor() | ||
+ | query = " | ||
+ | cur.execute(query) | ||
+ | for row in cur: | ||
+ | print(row) | ||
+ | |||
+ | cur.close() | ||
+ | </ | ||
+ | |||
+ | |||
+ | | ||
pythonpostgresql.1638196419.txt.gz · Last modified: 2025/03/08 22:23 (external edit)