如何在PostgreSQL中使用CSV文件导入和导出数据
在本文中,我们将看到如何在 PostgreSQL 中使用 CSV 文件导入和导出数据,使用 PostgreSQL 可以轻松导入和导出 CSV 文件中的数据。
要创建 CSV 文件,请打开任何文本编辑器(记事本、vim、atom)。在第一行写下列名。将用逗号分隔的行值添加到下一行中的相应列。将文件另存为 Demo_data.csv,如下所示。
现在使用 psycopg2 创建一个新表,我们将从 CSV 文件中导入数据:
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()
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()
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()
输出:
Table has been created successfully!!
使用 CSV 文件导入数据
我们使用带有 FROM 关键字的 COPY 命令将 CSV 文件的内容导入到新表中。
Syntax: COPY