Python读取写入postgresql数据库
使用pycharm先建立与PG数据库的连接:使用psycopg2包,我们建立table_word表,字段分别是url,title,time,content,使用url作为主键。代码如下## 导入psycopg2包import psycopg2## 连接到一个给定的数据库conn = psycopg2.connect(database="db", user="wjz",password="XXX",
·
使用pycharm先建立与PG数据库的连接:
使用psycopg2包,我们建立table_word表,字段分别是url,title,time,content,使用url作为主键。
代码如下
## 导入psycopg2包
import psycopg2
## 连接到一个给定的数据库
conn = psycopg2.connect(database="db", user="wjz",password="password", host="101.43.XXX.XXX", port="5432")
## 建立游标,用来执行数据库操作
cursor = conn.cursor()
## 执行SQL命令
cursor.execute("""CREATE TABLE if not exists table_word(
url varchar(60) PRIMARY KEY NOT NULL,
title varchar(30) NOT NULL,
time varchar(20) ,
content text)""")
insert_sql = "INSERT INTO table_word \
values('http://blog.sina.com.cn/s/blog_4462623d0102ze34.html','心智与觉醒','2021-12-23 12:23:42','test') \
on conflict on constraint table_word_pkey\
do nothing;"
cursor.execute(insert_sql)
## 提交SQL命令
conn.commit()
## 执行SQL SELECT命令
cursor.execute("select * from table_word")
## 获取SELECT返回的元组
rows = cursor.fetchall() #获取全部数据
# rows = cursor.fetchmany(size=500) #batch为500条数据进行获取
for row in rows:
print(row)
## 关闭游标
cursor.close()
## 关闭数据库连接
conn.close()
上述逻辑实现后,将insert插入数据包装为函数,使用excutemany批量插入数据,供爬虫数据后写入:
## 导入psycopg2包
import psycopg2
def insert_table(data):
## 连接到一个给定的数据库
conn = psycopg2.connect(database="db", user="wjz",password="password", host="101.43.XXX.XXX", port="5432")
## 建立游标,用来执行数据库操作
cursor = conn.cursor()
## 执行SQL命令
cursor.execute("""CREATE TABLE if not exists table_word(
url varchar(60) PRIMARY KEY NOT NULL,
title varchar(30) NOT NULL,
time varchar(20) ,
content text)""")
#do nothing是在主键冲突时防止SQL报错,若主键冲突则什么也不做
insert_sql = "INSERT INTO table_word values(%s,%s,%s,%s) \
on conflict on constraint table_word_pkey\
do nothing;"
cursor.executemany(insert_sql,data)
## 提交SQL命令
conn.commit()
# ## 执行SQL SELECT命令
# cursor.execute("select * from table_word")
#
# ## 获取SELECT返回的元组
# rows = cursor.fetchall() #获取全部数据
# # rows = cursor.fetchmany(size=500) #batch为500条数据进行获取
# for row in rows:
# print(row)
## 关闭游标
cursor.close()
## 关闭数据库连接
conn.close()
if __name__ == "__main__":
data = [['http://blog.sina.com.cn/s/blog_4462623d0102ze34.html', '心智与觉醒', '2021-12-23 12:23:42', 'test'],
['http://blog.sina.com.cn/s/blog_4462623d0102ze34.html', '心智与觉醒', '202sf12-23 12:23:42', 'test'],
['http://blog.sina.com.cn/s/blog_4462623d0102zeaa.html', '心智与fs', '2021-12-23 12:23:42', 'test']]
insert_table(data)
执行结果,查看数据:
更多推荐
已为社区贡献10条内容
所有评论(0)