python 向 pgSQL 导入 csv 文件

目录

一、正文

1. 安装 psycopg2 包

2. 运行以下代码

二、意外

1. 注释掉跳过表头

2. 采用跳过表头


一、正文

1. 安装 psycopg2 包

$ pip install psycopg2

2. 运行以下代码

注意将内容修改为自己的路径、数据表名、数据库名等。

如果不出意外的话,将会导入成功。

import psycopg2 as pg
resourcefilenames = 'E:\\college.csv'
targettablename = 'college'

conn = pg.connect(database="postgres", 
                user="postgres", 
                password="****", 
                host="127.0.0.1", 
                port="5432")

print("Opened database successfully")
cur = conn.cursor()
with open(resourcefilenames, 'r', encoding='utf-8') as f:
    # 跳过表头
    next(f)
    cur.copy_from(f, targettablename, sep=',', )
conn.commit()

端口号可以通过:...\PostgreSQL\15\data\postgresql.conf 文件查看,使用 vscode 可以打开 config 文件。

二、意外

1. 注释掉跳过表头

  1. csv 文件里面没有写表头,直接写的数据
  2. 运行以下代码
  3. 出现报错:错误:对于字符类型来说这个值太长了(4)
import psycopg2 as pg
resourcefilenames = 'E:\\college.csv'
targettablename = 'college'

conn = pg.connect(database="postgres", 
                user="postgres", 
                password="****", 
                host="127.0.0.1", 
                port="5432")

print("Opened database successfully")
cur = conn.cursor()
with open(resourcefilenames, 'r', encoding='utf-8') as f:
    # 跳过表头
    # next(f)
    cur.copy_from(f, targettablename, sep=',', )
conn.commit()

报错信息如下:

Traceback (most recent call last):
  File "e:\\college.py", line 16, in <module>
    cur.copy_from(f, targettablename, sep=',', )
psycopg2.errors.StringDataRightTruncation: 错误:  对于字符类型来说这个值太长了(4)
CONTEXT:  COPY college, line 1, column college_id: "1001"

事情非常离谱。我设置的该字段类型为 char(4),第一个字符串 “1001” 的长度也为 4,它居然说这个值太长了。但是当我将字符串 “1001” 删减为 “100” 时,即使后面的字符串均为 “100X”,居然就能插入成功。因此,我猜想是不是表首位置比较特别,可能有一些额外的字符我没有考虑到。故,我又采用了跳过表头的方式,希望能绕开特殊的表首位置。

2. 采用跳过表头

  1. csv 文件里面第一行为表头,后面跟着数据
  2. 运行以下代码
  3. 插入成功
import psycopg2 as pg
resourcefilenames = 'E:\\college.csv'
targettablename = 'college'

conn = pg.connect(database="postgres", 
                user="postgres", 
                password="****", 
                host="127.0.0.1", 
                port="5432")

print("Opened database successfully")
cur = conn.cursor()
with open(resourcefilenames, 'r', encoding='utf-8') as f:
    # 跳过表头
    next(f)
    cur.copy_from(f, targettablename, sep=',', )
conn.commit()

插入成功!

猜你喜欢

转载自blog.csdn.net/m0_64140451/article/details/129850437