前言

本文分享使用Python操作PostgreSQL数据库的基本方法,包括数据库连接、增、删、改、查,供各位小伙伴参考。


一、连接PostgreSQL数据库

操作MySQL数据库主要使用psycopg2包,连接PostgreSQL数据库的语法为connect(IP, 端口, 用户名, 密码, 数据库名,编码格式)。具体代码如下:

import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

二、增

(一)建表

  1. 创建mysql连接:pymysql.connect(),详见上文第一点
  2. 创建游标:conn.cursor()
  3. 编写建表语句,建表语句写在三引号中
    (1)create_sql = “”“xxx”“”
    (2)cursor.execute(create_sql)
  4. 提交语句:conn.commit()
  5. 关闭mysql连接:conn.close()
import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

# 建表
create_sql = """
    CREATE TABLE xxx.yyy(
        id int
       ,name varchar(10)
    );
"""

cursor.execute(create_sql)
print("create successfully")

conn.commit()
conn.close()

(二)插入数据

  1. 插入单条数据的语法和sql的插入类似,直接键值对插入,插入语句写在双引号中。具体代码如下:
import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

# 插入
insert_sql = "INSERT INTO xx.yyy (id, name) VALUES (%s, '%s')" % (1, '张三')

cursor.execute(insert_sql)
print("insert successfully")

conn.commit()
conn.close()
  1. 查询插入数据,适用于从数据库其他表查询关联后插入数据到新表。插入语句写在三引号中。具体代码如下:
import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

# 插入
insert_sql = """
    DROP TABLE IF EXISTS xx.yyy;
    CREATE TABLE IF NOT EXISTS xx.yyy AS
    SELECT
        aa
       ,bb
    FROM xx.yyy
"""

cursor.execute(insert_sql)
print("insert successfully")

conn.commit()
conn.close()

三、删

(一)删表

直接删除表数据和表结构,其语法和SQL删表语法一致。具体代码如下:

import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

# 删表
cursor.execute("DROP TABLE IF EXISTS xx.yyy")

conn.commit()
conn.close()

(二)删除表数据

只删除数据,不删除表结构。其语法和SQL删表数据语法一致。具体代码如下:

import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

# 删表数据
cursor.execute("TRUCATE TABLE xx.yyy")

conn.commit()
conn.close()

三、改

(一)更新数据

将上文所建的yyy表中,“张三”改为“何老六”。具体代码如下:

import psycopg2

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)

cursor = conn.cursor()

cursor.execute("UPDATE xx.yyy SET name = '何老六' WHERE id = 1")

conn.commit()
conn.close()

(二)结果展示

Python操作PostgreSQL数据库-LMLPHP
Python操作PostgreSQL数据库-LMLPHP

四、查

(一)查询数据库表

直接使用pandas包查询数据库表,语法为read_sql(“select xxx from yyy”, con=数据库连接)。

import psycopg2
import pandas as pd

conn = psycopg2.connect(
    host='xxx',
    port='xxx',
    dbname='xxx',
    user='xxx',
    password='xxx'
)
df = pd.read_sql("select * from xx.yyy limit 100;", con=conn)

print(df)


总结

除了PostgreSQL数据库外,业界常用的数据库MySQL也可以使用Python进行操作,具体情况可参考作者的另一篇博客Python操作MySQL数据库

04-26 23:53