Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Database
  • Python MySQL
  • Python SQLite
  • Python MongoDB
  • PostgreSQL
  • SQLAlchemy
  • Django
  • Flask
  • SQL
  • ReactJS
  • Vue.js
  • AngularJS
  • API
  • REST API
  • Express.js
  • NodeJS
Open In App
Next Article:
Python PostgreSQL - Limit Clause
Next article icon

Python – Import CSV into PostgreSQL

Last Updated : 23 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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              ', '[email protected]', 60000.0)  (2, 'pratyusha           ', '[email protected]', 75000.0)  (3, 'pratibha            ', '[email protected]', 65000.0)


Next Article
Python PostgreSQL - Limit Clause
author
isitapol2002
Improve
Article Tags :
  • Python
  • Python PostgreSQL
  • Python Pyscopg2
Practice Tags :
  • python

Similar Reads

  • Python PostgreSQL - Limit Clause
    In this article, we are going to see how to use the limit clause in PostgreSQL using pyscopg2 module in Python. In PostgreSQL LIMIT constraints the number of rows returned by the query. By default, It is used to display some specific number of rows from the top. If we want to skip a number of rows b
    2 min read
  • Insert Python list into PostgreSQL database
    In this article, we will discuss how to Insert a Python list into PostgreSQL database using pyscopg2 module. Psycopg2 is the most popular PostgreSQL adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-
    2 min read
  • PostgreSQL - Create Tables in Python
    Creating tables in PostgreSQL using Python is an essential skill for developers working with databases. This article will explore the process of creating new tables in the PostgreSQL database using Python. Why Create PostgreSQL Tables with Python?Using Python to create PostgreSQL tables is beneficia
    4 min read
  • Python PostgreSQL - Order By
    In this article, we will discuss how to use order by clause in PostgreSQL using python. The Order By clause is used to sort the records of a table returned by the SELECT clause in ascending order by default, yet asc keyword can be used. If we want to sort the records in descending order then we have
    3 min read
  • Perform PostgreSQL CRUD operations from Python
    The DDL is comprised of the Create, Read, Update, Delete (CRUD) operations which form the backbone of any SQL database system. Let us discuss how to perform CRUD operations on a PostgreSQL database using python.  Pyscopg2 is the most preferred mode and is widely used to connect the PostgreSQL databa
    7 min read
  • Python PostgreSQL - Delete Data
    In this article, we are going to see how to delete data in tables from PostgreSQL using pyscopg2 module in Python. In PostgreSQL, DELETE TABLE is used to delete the data in the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constr
    2 min read
  • Python | Database management in PostgreSQL
    PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Py
    6 min read
  • Python PostgreSQL - Drop Table
    In this article, we are going to see how to drop tables in PostgreSQL using pyscopg2 module Python. In PostgreSQL DROP TABLE is used to remove the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constraints for that table. If the p
    2 min read
  • Handling PostgreSQL BLOB data in Python
    In this article, we will learn how to Handle PostgreSQL BLOB data in Python. BLOB is a Binary large object (BLOB) is a data type that can store any binary data.To store BLOB data in a PostgreSQL database, we need to use the Binary Large Object (BLOB) data type.By using the Binary Large Object (BLOB)
    5 min read
  • Python PostgreSQL - Where Clause
    In this article, we are going to see how to use the Where clause in PostgreSQL using Psycopg2 in Python. Where Clauses help us to easily deal with the databases. As we know we have a huge amount of data stored in our database, so extracting only useful and required information clauses is helpful. Th
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences