Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to import and export data using CSV files in PostgreSQL

How to import and export data using CSV files in PostgreSQL

In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL.

To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separated by commas to the corresponding columns in the next lines. Save the file as Demo_data.csv as shown below.

Now create a new table using psycopg2 where we will import the data from the CSV file:

Python3




import psycopg2
  
# connection establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to create a table
sql = ''' CREATE TABLE demo
(
    id INT,
    name VARCHAR(50),
    city VARCHAR(50),
    age INT
); '''
  
# executing above query
cursor.execute(sql)
print("Table has been created successfully!!")
  
# Closing the connection
conn.close()


Output:

Table has been created successfully!!

Importing data using a CSV file

We use COPY command with FROM keyword to import the contents of the CSV file into a new table.

Syntax: COPY <table name> FROM ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;

Where:

  • <table name> – name of the table where we want to import data.
  • ‘location + file_name’ – full path of the CSV file from which we are importing data (make sure you have ‘read’ access to the file).
  • DELIMITER ‘,’ – specifies the delimiter which is comma (,)
  • CSV – specifies the format of the file from which we are importing data.
  • HEADER – specifies that we have a header row in our .csv file and while importing we should ignore the first row.

Example:

Python3




import psycopg2
  
# connection establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to import data from given csv
sql = '''COPY demo FROM 
        'C:\\Users\\DELL\\Downloads\\Demo_data.csv' 
        DELIMITER ',' CSV HEADER'''
  
# executing above query
cursor.execute(sql)
  
# Display the table
cursor.execute('SELECT * FROM demo')
print(cursor.fetchall())
  
# Closing the connection
conn.close()


Output:

[(1, ‘Harry’, ‘Delhi’, 29), (2, ‘Mira’, ‘Mumbai’, 24), (3, ‘Emma’, ‘Bangalore’, 30), (4, ‘Kevin’, ‘Mumbai’, 19)]

Exporting data using CSV file

To export data from a table into a CSV file, we use TO keyword with the COPY command. 

Syntax: COPY <table name> TO ‘location + file_name’ DELIMITER ‘,’ CSV HEADER;

Here, <table name> is the table from which we are exporting data.

‘location + file_name’ contains the path of the CSV file into which we want to export the data. Make sure you have ‘write’ access to the file.

Example:

Python3




import psycopg2
  
# connection establishment
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
conn.autocommit = True
  
# Creating a cursor object
cursor = conn.cursor()
  
# query to export table into csv
sql = '''COPY demo TO 
        'C:\\Users\\DELL\\Downloads\\Exported_data.csv' 
        DELIMITER ',' CSV HEADER'''
  
# executing above query
cursor.execute(sql)
  
# Closing the connection
conn.close()


The exported CSV will look like this:

RELATED ARTICLES

Most Popular

Recent Comments