473,569 Members | 2,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3619
In article <pa************ *************** *@augustmail.co m>, 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(da tabase='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.descript ion]
rows = cursor.fetchall ()
data = [dict(zip(colnam es, 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(N one, "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 'cGV0ZXIubWFhc0 BtcGx1c3IuZGU=\ n'.decode('base 64')
-------------------------------------------------------------------
Jul 18 '05 #4
Lance Hoffmeyer <la********@aug ustmail.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("SE LECT 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
3624
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 always returns things like, "Are you sure the server is running locally?", etc. What's the magic chant to connect to PostgreSQL over UNIX domain...
3
4171
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 machine I get a message that the remote machine IP address is not specified in pg_hba.conf, that there is no record of that machine there....
2
1785
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 written in python, I get a "server closed the connection unexpectedly" exception after executing a few sql commands. I print each query before I execute...
1
3264
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 /usr/share/pgsql/pg73b1jdbc2.jar:/usr/share/pgsql/pg73b1jdbc3.jar JDBC Driver Class org.postgresql.Driver
1
2195
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 open up postgresql to the internet. So, I'd like to tunnel the libpq connection over the existing secure socket. My preferred solution would be...
0
862
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
3508
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: Could not connect to server: permission denied. Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432" I...
1
5465
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 Files/PostgreSQL/8.0.0-beta4/data/pg_hba.conf" at line 64, token "192.168.2.1/254"
3
7784
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 SSH(secure shell) Dim myPgrConnect As New NpgsqlConnection("Server=localhost; Port=8443; Database=dalitch_css; User Id=dalitch; Password=dfndev;...
0
7605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7917
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7665
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6277
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2105
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.