Basic connection to PostgreSQL with psycopg : PostgreSQL « Database « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » Database » PostgreSQL 
15.4.2.Basic connection to PostgreSQL with psycopg
import psycopg

def getdsn(db = None, user = None, passwd = None, host = None):
    if user == None:
        import os, pwd
        user = pwd.getpwuid(os.getuid())[0]
    if db == None:
        db = user

    dsn = 'dbname=%s user=%s' % (db, user)
    if passwd != None:
        dsn += ' password=' + passwd
    if host != None:
        dsn += ' host=' + host
    return dsn

dsn = getdsn()
print "Connecting to %s" % dsn
dbh = psycopg.connect(dsn)
print "Connection successful."
dbh.close()
15.4.PostgreSQL
15.4.1.Query data
15.4.2.Basic connection to PostgreSQL with psycopg
15.4.3.Query PostgreSQL database with select statement
15.4.4.Create a table and insert data
15.4.5.executemany() for batch update
15.4.6.optimized execute() for multiple rows example
15.4.7.Fetch all rows after query
15.4.8.Adjust the connect() call below for your database
15.4.9.Fetch row one by one
15.4.10.Fetch row by using cursor
15.4.11.Parameter style
15.4.12.Get cursor
15.4.13.Using types to insert data
15.4.14.Commit example
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.