附录2:调用示例
import os
import sys
import psycopg2
#数据库操作
def connectVastbase():
#连接数据库
conn = psycopg2.connect(database="postgres", user="vastbase2", password="Aa@123456", host="127.0.0.1", port="25432")
print('connect successful!')
cursor = conn.cursor()
#创建表
cursor.execute("create table tb_test(id integer not null primary key, name text)")
print('create table successful!')
#插入数据
cursor.execute("insert into tb_test(id, name) values(1, 'Anna')")
cursor.execute("insert into tb_test(id, name) values(%s, '%s')" %(2, 'Jack'))
conn.commit()
print('insert successful!')
#查询数据
cursor.execute("select * from tb_test")
#fetchall
records = cursor.fetchall()
for record in records:
print('fetchall: id = ' + str(record[0]) + ', name = ' + str(record[1]))
#fetchone
cursor.execute("select * from tb_test")
record = cursor.fetchone()
print('fetchone: id = ' + str(record[0]) + ', name = ' + str(record[1]))
#fetchmany
cursor.execute("select * from tb_test")
records = cursor.fetchmany(10)
for record in records:
print('fetchmany: id = ' + str(record[0]) + ', name = ' + str(record[1]))
#rollback
cursor.execute("insert into tb_test(id, name) values(3, 'Mike')")
conn.rollback()
cursor.execute("select * from tb_test")
records = cursor.fetchall()
for record in records:
print('atfer rollback: id = ' + str(record[0]) + ', name = ' + str(record[1]))
#更新数据
cursor.execute("update tb_test set name = '%s' where id = 1" %('Elsa'))
print('update successful!')
cursor.execute("select * from tb_test")
records = cursor.fetchall()
for record in records:
print('after update: id = ' + str(record[0]) + ', name = ' + str(record[1]))
#删除数据
cursor.execute("delete from tb_test where id = 2")
conn.commit()
cursor.execute("select * from tb_test")
records = cursor.fetchall()
for record in records:
print('after delete: id = ' + str(record[0]) + ', name = ' + str(record[1]))
cursor.close()
conn.close()
if __name__=='__main__':
connectVastbase()