
如何将此类数据轻松导入 postgresql
作为新手,您可能想了解如何将特定格式的数据导入数据库,例如 postgresql。以下是如何操作:
# 创建表 create table info ( code char(50), topic varchar(50), author varchar(50) ); # 使用 load data infile 命令导入数据 load data infile 'data.txt' into table info fields terminated by ',' lines terminated by '\n';
postgresql
使用 postgresql 的 python 驱动程序:
import psycopg2
# 连接到数据库
conn = psycopg2.connect(
"host=localhost",
"user=postgres",
"password=password",
"database=mydatabase"
)
# 创建游标
cur = conn.cursor()
# 创建表
cur.execute("CREATE TABLE info (code CHAR(50), topic VARCHAR(50), author VARCHAR(50))")
# 准备插入语句
stmt = conn.prepare("INSERT INTO info VALUES ($1, $2, $3)")
# 逐行插入数据
with open('data.txt') as f:
for line in f:
parts = line.split(',')
stmt(parts[0], parts[1], parts[2])
# 提交事务
conn.commit()
# 关闭连接
conn.close()以上就是如何将数据轻松导入 PostgreSQL?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号