473,413 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

Connecting to a postgresql DB?

Hello,

I am trying to learn some basics of python. One of the things
I want to do is write a script to access a postgresql database
DB as user USER with password PW and

SELECT first_name, last_name, birthday FROM contacts

print to the screen and then disconnect.
Can someone show me an example of how to do this?

Lance

Jul 18 '05 #1
4 3611
In article <pa****************************@augustmail.com>, Lance Hoffmeyer
wrote:
I am trying to learn some basics of python. One of the things
I want to do is write a script to access a postgresql database
DB as user USER with password PW and

SELECT first_name, last_name, birthday FROM contacts

print to the screen and then disconnect.


This assumes you have the standard postgresql-python package. You may also
want to try psycopg or pyPgSQL.
import pgdb
conn = pgdb.connect(database='DB', user='USER', password='PW')
cursor = conn.cursor()
cursor.execute("SELECT first_name, last_name, birthday FROM contacts")
colnames = [t[0] for t in cursor.description]
rows = cursor.fetchall()
data = [dict(zip(colnames, row)) for row in rows]
print data


Dave Cook
Jul 18 '05 #2
Lance Hoffmeyer:
I am trying to learn some basics of python. One of the things
I want to do is write a script to access a postgresql database [...]Can someone show me an example of how to do this?


Google!

http://www.python.org/peps/pep-0249.html
http://pypgsql.sourceforge.net/README.html
http://www.google.nl/search?q=cache:...+example&hl=nl

--
René Pijlman
Jul 18 '05 #3
Lance Hoffmeyer schrieb:
I am trying to learn some basics of python. One of the things
I want to do is write a script to access a postgresql database
DB as user USER with password PW and

SELECT first_name, last_name, birthday FROM contacts

print to the screen and then disconnect.


URLs for required modules:

- mxDateTime
http://www.egenix.com/files/python/e...xtensions.html
- pypgSQL:
http://sourceforge.net/project/showf...group_id=16528

Example code:

#!/usr/bin/env python
# -*- coding: latin-1 -*-

"""
Example code for reading data from a PostgreSQL database. This
code requires the modules mxDateTime and pyPgSQL (DB-API 2.0
compliant so that the calls are not database dependent except
of connection URL and some SQL capabilities).
"""

# PostgreSQL interface module
from pyPgSQL import PgSQL

if __name__ == '__main__':
# open connection
con = PgSQL.connect(None, "aUser", "aPasswd", "aHost", "aDatabase")

# create cursor
c_adr = con.cursor()

# let cursor execute an SQL command
c_adr.execute("SELECT * FROM address")

# fetch a result set
r_adr = c_adr.fetchmany(10)

# The result set is a list of records.
print r_adr[0]

# Each record is a dictionary like object with field names as keys.
print r_adr[0].keys()

# The field values are the dictionary values.
print r_adr[0]["firstname"]

# print all records
for record in r_adr:
print record
Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Jul 18 '05 #4
Lance Hoffmeyer <la********@augustmail.com> wrote:

I am trying to learn some basics of python. One of the things
I want to do is write a script to access a postgresql database
DB as user USER with password PW and

SELECT first_name, last_name, birthday FROM contacts

print to the screen and then disconnect.

Can someone show me an example of how to do this?


Postgres support is not built-in to Python. You'll need to install one of
the Postgres packages, like pgdb or pypgsql or psycopg. They are all
compliant with the Python DBAPI spec, so the usage is pretty similar:

import psycopg

db = psycopg.connect("dbname=db user=USER password=PW")
cur = db.cursor()
cur.execute("SELECT first_name, last_name, birthday FROM contacts")

for first,last,bday in cur.fetchall():
print "%s %s has birthday %s" % (first, last, bday)
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: afalanga | last post by:
Hi, I seem to be unable to connect to my PostgreSQL database over UNIX domain sockets, i.e. pg_connect("dbname=mydb"); No matter what I do to the pg_hba.conf file, or anything else, PHP...
3
by: N.K. | last post by:
Hi, I've just installed postgres on the Linux server. It is supposed to start automatically which I think it does since I can run an sql stmt right away. When I'm trying to connect from a remote...
2
by: Jeff | last post by:
I have the following packages installed on my system: libpq3: 7.3.2r1-5 python-pygresql: 7.3.2r1-5 postgresql: 7.2.1-2woody2 postgresql-client: 7.2.1-2woody2 In my application, which is...
1
by: tim | last post by:
I have problems to connect my postgres db in Openoffice 1.1 via jdbc. I can open the tables and run queries. But when try to create or alter tables OpenOffice crashes. My Settings ClassPath...
1
by: jbi130 | last post by:
I have a 3 tier client/server application where the client connection to the server which then uses PostgreSQL. I'd like to extend the client to have direct access to PostgreSQL but do not want to...
0
by: Hale | last post by:
how do I connect to an external postgresql db on ip 1.2.3.4 using DBI and perl? any other ways to do it in per?
6
by: Alexander Cohen | last post by:
Im trying to connect locally to a database on a running postgres cluster. If i connect with psql, everything is fine and i can transact. I i try and connect in my own app, i get this error: ...
1
by: Goutam Paruchuri | last post by:
Hello, I get an error in my log when connecting to postgres server on Windows. Postgres version : 8.0.0-beta4 LOG TEXT 2004-11-10 11:22:47 LOG: invalid entry in file "C:/Program...
3
by: rhepsi | last post by:
Hii all, im doin a vb 1.1 vs.net 2003 project where im trying to update the data from mysql to postgreSQL.... when im trying to click on update , im opening the connection of PostgreSQL using...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.