Thursday, June 6, 2019

Python - PostgreSQL DB connection


Hello friends , in this blog post we will learn how to connect python with PostgreSQL.PostgreSQL is a powerful, open source object-relational database system that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads.PostgreSQL has earned a strong reputation for its proven architecture, reliability, data integrity, robust feature set, extensibility, and the dedication of the open source community behind the software to consistently deliver performant and innovative solutions. PostgreSQL runs on all major operating systems, has been ACID-compliant since 2001.


Step 1 : ) Create a table in PostgreSQL , here we have created a table called test.



Step 2 :) import module psycopg2 module from python repository

Type ‘pip install psycopg2’ from command line terminal

Step 3:) The required code to connect python with PostgreSQL.

import psycopg2

def connect():
conn_string = "host='localhost' dbname='postgres' user='postgres' password='postgres'"
print ("Print the connection details \n ->%s" % (conn_string))
conn = psycopg2.connect(conn_string)
cursor = conn.cursor()
cursor.execute("SELECT * FROM test")
display_data=cursor.fetchall()
print(display_data)
cursor.close()
if __name__== '__main__':

connect()


Step 4:) We can check the output on the console.



No comments:

Post a Comment

Hadoop - What is a Job in Hadoop ?

In the field of computer science , a job just means a piece of program and the same rule applies to the Hadoop ecosystem as wel...