如何将数据轻松导入 PostgreSQL?
数据库小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《如何将数据轻松导入 PostgreSQL?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
如何将此类数据轻松导入 postgresql
作为新手,您可能想了解如何将特定格式的数据导入数据库,例如 postgresql。以下是如何操作:
mysql
# 创建表 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?》,希望本文对你有所帮助!关注主机宝贝公众号,给大家分享更多数据库知识!