1import psycopg2
2try:
3 connection = psycopg2.connect(user = "sysadmin",
4 password = "pynative@#29",
5 host = "127.0.0.1",
6 port = "5432",
7 database = "postgres_db")
8
9 cursor = connection.cursor()
10 # Print PostgreSQL Connection properties
11 print ( connection.get_dsn_parameters(),"\n")
12
13 # Print PostgreSQL version
14 cursor.execute("SELECT version();")
15 record = cursor.fetchone()
16 print("You are connected to - ", record,"\n")
17
18except (Exception, psycopg2.Error) as error :
19 print ("Error while connecting to PostgreSQL", error)
20finally:
21 #closing database connection.
22 if(connection):
23 cursor.close()
24 connection.close()
25 print("PostgreSQL connection is closed")
1import psycopg2
2from psycopg2 import Error
3
4try:
5 connection = psycopg2.connect(user = "postgres",
6 password = "pass@#29",
7 host = "127.0.0.1",
8 port = "5432",
9 database = "postgres_db")
10
11 cursor = connection.cursor()
12
13 create_table_query = '''CREATE TABLE mobile
14 (ID INT PRIMARY KEY NOT NULL,
15 MODEL TEXT NOT NULL,
16 PRICE REAL); '''
17
18 cursor.execute(create_table_query)
19 connection.commit()
20 print("Table created successfully in PostgreSQL ")
21
22except (Exception, psycopg2.DatabaseError) as error :
23 print ("Error while creating PostgreSQL table", error)
24finally:
25 #closing database connection.
26 if(connection):
27 cursor.close()
28 connection.close()
29 print("PostgreSQL connection is closed")
1from sqlalchemy import create_engine
2engine = create_engine('postgresql://postgres:admin1@localhost:5432/postgres')