Thursday, July 4, 2024
HomeLanguagesPythonPython – Import CSV into PostgreSQL

Python – Import CSV into PostgreSQL

In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2.

First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the “create table” SQL command using the cursor.execute() method.

'''CREATE TABLE DETAILS(employee_id int NOT NULL,
                        employee_name char(20), 
                        employee_email varchar(30),
                        employee_salary float);'''

View of the empty table:

Table Description

After creating the table we need to execute the “copy” command in the SQL form. in the copy command, we need to specify the path of the CSV file. 

CSV File Used:

CSV File Used

'''COPY table_name
FROM 'C:\folder\file.csv' 
DELIMITER ',' 
CSV HEADER;'''

Below is the implementation:

Python3




import psycopg2
  
conn = psycopg2.connect(database="EMPLOYEE_DATABASE",
                        user='postgres', password='pass'
                        host='127.0.0.1', port='5432'
)
  
conn.autocommit = True
cursor = conn.cursor()
  
  
sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\
employee_name char(20),\
employee_email varchar(30), employee_salary float);'''
  
  
cursor.execute(sql)
  
sql2 = '''COPY details(employee_id,employee_name,\
employee_email,employee_salary)
FROM '/private/tmp/details.csv'
DELIMITER ','
CSV HEADER;'''
  
cursor.execute(sql2)
  
sql3 = '''select * from details;'''
cursor.execute(sql3)
for i in cursor.fetchall():
    print(i)
  
conn.commit()
conn.close()


Output:

(1, 'rajesh              ', 'rajesh89@gmail.com', 60000.0)
(2, 'pratyusha           ', 'praty@gmail.com', 75000.0)
(3, 'pratibha            ', 'pratibhaJ@gmail.com', 65000.0)
Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments