使用python将数据导入postgresql数据中

1 插入一条数据

  1. 连接postgresql数据库中的origindb数据库,用户为dn。
  2. 创建表
  3. 插入一条数据
## 导入psycopg2包
import psycopg2

## 连接到一个给定的数据库
conn = psycopg2.connect(database="origindb", user="dn", password="000000", host="192.168.10.102", 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)

## 关闭游标

你可能感兴趣的:(postgresql,python,数据库)