更新时间:2026-07-28 GMT+08:00
数据库建连、执行SQL并返回结果
非透明多写特性下行为结果
本示例演示在Python驱动下连接数据库、建表、插入数据并返回结果的常规操作。
# 本示例以用户名和密码保存在环境变量中为例,运行本示例前请先在环境中设置环境变量EXAMPLE_USERNAME_ENV和EXAMPLE_PASSWORD_ENV。
# 用户需要提供dbname="database"数据库名、port=数据库端口号、host="localhost"表示数据库在本地机器上运行。
# 关于证书等文件的获取,请登录GaussDB管理控制台,在“实例管理”页面,单击实例名称进入“基本信息”页面,单击“SSL”处的下载图标,下载根证书或捆绑包,并将根证书ca.pem放置在客户端。
import psycopg2
import os
import ssl
# 从环境变量中获取host和port。
host = "localhost"
port = os.getenv('EXAMPLE_PORT_ENV')
# 从环境变量中获取用户名和密码。
userName = os.getenv('EXAMPLE_USERNAME_ENV')
passWord = os.getenv('EXAMPLE_PASSWORD_ENV')
# 以非加密方式连接数据库。
conn = psycopg2.connect(dbname="database", user=userName, password=passWord, host=host, port=port)
# 用户需要使用SSL方式连接数据库,则采用本行代码。
# conn = psycopg2.connect(dbname="database", user=userName, password=passWord, host=host, port=port,sslmode="verify-ca", sslrootcert="ca.pem")
# 创建游标对象。
cur=conn.cursor()
# 创建表。
cur.execute("CREATE TABLE student(id integer,name varchar,gender varchar)")
# 插入数据。
cur.execute("INSERT INTO student(id,name,gender) VALUES(%s,%s,%s)",(1,'Aspirin','M'))
cur.execute("INSERT INTO student(id,name,gender) VALUES(%s,%s,%s)",(2,'Taxol','F'))
cur.execute("INSERT INTO student(id,name,gender) VALUES(%s,%s,%s)",(3,'Dixheral','M'))
# 批量插入数据。
stus = ((4,'John','M'),(5,'Alice','F'),(6,'Peter','M'))
cur.executemany("INSERT INTO student(id,name,gender) VALUES(%s,%s,%s)",stus)
# 更新数据。
cur.execute("UPDATE student SET name=%s WHERE id=%s", ('Aspirin Updated', 1))
# 删除数据。
cur.execute("DELETE FROM student WHERE id=%s", (2,))
# 获取结果。
cur.execute('SELECT * FROM student')
results=cur.fetchall()
print (results)
# 提交操作。
conn.commit()
# 插入一条数据。
cur.execute("INSERT INTO student(id,name,gender) VALUES(%s,%s,%s)",(7,'Lucy','F'))
# 回退操作。
conn.rollback()
# 关闭游标和连接。
cur.close()
conn.close() 示例运行结果如下:
[(1, 'Aspirin Updated', 'M'), (3, 'Dixheral', 'M'), (4, 'John', 'M'), (5, 'Alice', 'F'), (6, 'Peter', 'M')]
父主题: 典型应用开发示例