User Tools

Site Tools


pythonpostgresql

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
pythonpostgresql [2021/11/29 21:45] z0hpvkpythonpostgresql [2025/03/08 22:24] (current) – external edit 127.0.0.1
Line 3: Line 3:
 [[https://pypi.org/project/psycopg2/|psycopg2 Installation]]\\ [[https://pypi.org/project/psycopg2/|psycopg2 Installation]]\\
  
 +=== Connecting to PostgreSQL ===
 <code python> <code python>
 import psycopg2 import psycopg2
Line 25: Line 26:
 </code> </code>
  
-<code>+=== Example Connection Files === 
 +== Using Config Parser == 
 +<code python>
 # database.ini # database.ini
 [postgresql] [postgresql]
Line 33: Line 36:
 password=pwd password=pwd
 </code> </code>
- 
 <code python> <code python>
 #!/usr/bin/python #!/usr/bin/python
Line 47: Line 49:
   return db   return db
 </code> </code>
 +
 +<code python>
 +#!/usr/bin/python
 +from config import config
 +
 +def connect()
 +  conn = None
 +  try:
 +    params = config()
 +    conn = psycopg2.connect(**params)
 +    cur = conn.cursor()
 +    cur.execute('SELECT version()')
 +    db_version = cur.fetchone()
 +    print(db_version)
 +    cur.close()
 +  except (Exception, psycopg2.DatabaseError) as error:
 +    print(error)
 +</code>
 +
 +== Using Credential File ==
 +<code python>
 +# conndetails.py
 +PGHOST="localhost"
 +PGDATABASE="doob"
 +PGUSER="ian"
 +PGPASSWORD="pwd"
 +</code>
 +
 +<code python>
 +import psycopg2
 +import conndetails as creds
 +
 +conn_string = "host="+ creds.PGHOST +" dbname="+ creds.PGDATABASE +" user=" 
 +               + creds.PGUSER +" password="+ creds.PGPASSWORD
 +conn = psycopg2.connect(conn_string)
 +
 +cur = conn.cursor()
 +query = "select version()"
 +cur.execute(query)
 +for row in cur:
 +  print(row)
 +
 +cur.close() 
 +</code>
 +
 +
 +    
  
pythonpostgresql.1638222349.txt.gz · Last modified: 2025/03/08 22:23 (external edit)