
如何将异构数据格式导入 postgresql 数据库
作为一名新手,您希望将复杂的数据格式导入数据库,例如 postgresql。这个问题可以从以下两个角度来解决: 和 postgresql。
mysql
1. 创建数据库和表:
create database my_database; create table my_table ( code char(50), topic char(50), author char(50) );
登录后复制
2. 使用 load data infile 命令导入数据:
load data infile 'data.txt' into table my_table fields terminated by ' ';
登录后复制
postgresql
转换为 postgresql 的 版驱动程序后,您可以通过以下方式批量导入:
1. 创建数据库和表:
import psycopg2
# 连接 postresql 数据库
conn = psycopg2.connect(
host="localhost",
port=5432,
database="my_database",
user="my_user",
password="my_password"
)
cur = conn.cursor()
# 创建表
cur.execute("create table info (code char(50), topic char(50), author char(50))")
登录后复制
2. 导入数据:
# 创建一个准备好的语句对象
stmt = conn.cursor("insert into info values (%s, %s, %s)")
# 使用可迭代对象批量插入数据
rows = [
["007", "the paron lal", "pardon110|candy"],
["008", "the paron lal 2", "pardon110|candy 2"]
]
stmt.executemany("insert into info values (%s, %s, %s)", rows)
登录后复制
3. 提交更改:
conn.commit() # 关闭连接 cur.close() conn.close()
登录后复制
以上就是如何将异构数据格式导入PostgreSQL数据库?的详细内容,更多请关注米云网其它相关文章!
