Python Programming to Connect Postgresql database

Python Programming to Connect Postgresql database

In python programming, below code is used to read data from Postgresql database tables.

#!/usr/bin/python

import psycopg2

employees = []
//Creates the database connection object.
db_con = psycopg2.connect(database = "database_name", user = "db user name", password = "db user password", host = "server ip or name")

cur = db_con.cursor()

//Executes the sql command
cur.execute("select emp.first_name + ' ' + emp.last_name as employee_name,"+
	    "emp.start_date, emp.end_date, dp.designation, emp.salary, emp.email "+
	    "from employees emp "+
	    "join department dp on (emp.employee_id = dp.employee_id) "+
	    "where dp.department_id = '2';"
rows = cur.fetchall()
for row in rows:
    obj = {}
    obj.update({"name": row[0],"start_date": row[1],"end_date": row[2],"designation": row[3],"salary": row[4],"email": row[5]})
    employees.append(obj)

db_con.close()

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^