ITPub博客

首页 > 数据库 > PostgreSQL > 如何使用python3写一个连接瀚高数据库的测试小脚本

如何使用python3写一个连接瀚高数据库的测试小脚本

原创 PostgreSQL 作者:瀚高PG实验室 时间:2021-05-19 14:58:00 0 删除 编辑

近期需要做一个绑定变量的测试,用python简单写了一个测试脚本,用于模拟程序插入数据到数据库,程序内容如下:

#导入psycopg2包和UUID包
import psycopg2
import uuid
import datetime
import time
#连接到一个给定的数据库
conn = psycopg2.connect(database="highgo", user="highgo", password="xxxxxxx", host="192.xx.xx.xx.xx", port="5866")
#建立游标,用来执行数据库操作
cursor = conn.cursor()
#执行SQL命令
#cursor.execute("select * from var_test")
var1=uuid.uuid1()
tim=datetime.datetime.now()
#以下为几种不同的插入数据方式
#cursor.execute("INSERT INTO var_test values(1,'%s',now())" %(var1))
#cursor.execute("INSERT INTO var_test values(2,'%s',now())" %uuid.uuid1())
#cursor.execute("INSERT INTO var_test values(%s,'%s','%s')" %(20,var1,tim))
sql_update="update var_test set id ="
cursor.execute("INSERT INTO var_test values(?,?,?)" %(20,var1,tim))
#time.sleep(10)
#提交SQL命令
conn.commit()
cursor.execute("select * from var_test where id=20")
#获取SELECT返回的元组
rows = cursor.fetchall()
for row in rows:
    print ('ID号:',row[0], '序列号:', row[1],  '插入时间:',row[2],'\n')
#关闭游标
cursor.close()
#关闭数据库连接
conn.close()
#print uuid.uuid5(uuid.NAMESPACE_DNS,'test')

注意:指定字符集为gbk,可以解决插入中文显示乱码问题。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69994931/viewspace-2772950/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
瀚高PG实验室(Highgo PG Lab)依托于瀚高DBA运维团队及瀚高数据库PG内核研发团队,旨在深入研究PostgreSQL技术、使用技巧、内核探秘、PG教学等,并进行分享。欢迎大家关注、交流。

注册时间:2021-02-18

  • 博文量
    184
  • 访问量
    126085