postgresql 与python插入空值
插入数据时,处理空值对 postgresql 和 python 非常重要。空值既可以表示 null,也可以表示空字符串 ""。
将空字符串替换为 null
在 postgresql 中,空字符串 "" 被视为非空值。为了将空字符串替换为 null,可以使用 replace() 方法:
立即学习
“
Python免费学习笔记(深入)
”;
Python 3.14.3
微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。
下载
通过这种方式,空字符串将被替换为 null,并正确插入数据库。
处理其他空值(例如 nan、none)
对于其他空值(例如 numpy 中的 np.nan、python 中的 none),必须在插入数据前对其进行处理。一种方法是使用 isnull() 和 coalesce() 函数:
通过这种方法,np.nan 和 none 将被转换为 sql null 值,并插入数据库。
import psycopg2
# 连接到数据库
conn = psycopg2.connect(...)
# 创建游标
cur = conn.cursor()
# 将空字符串替换为 null
query = """
insert into student (name, age)
values (%s, %s)
on conflict do nothing
"""
values = (none, 15) # 空字符串 none 将被替换为 null
cur.execute(query, values)
# 提交更改
conn.commit()import pandas as pd
import psycopg2
# 加载数据帧
df = pd.DataFrame(...)
# 处理空值
df['column_name'] = df['column_name'].isnull().astype('int')
# 转换为 SQL 值
values = list(df.to_dict('records').values())
# 构造查询
query = """
INSERT INTO table_name (column1, column2)
VALUES %s
"""
cur.executemany(query, values)