下面展示一些 代码。
// An highlighted block
var foo = 'bar';
import psycopg2
#获得连接
conn=psycopg2.connect(database='postgres',user='postgres',password='131415',host='127.0.0.1',port='5432')
#获得游标对象
cursor=conn.cursor()
#sql语句
sql='SELECT VERSION()'
#执行语句
cursor.execute(sql)
#获取单条数据
data=cursor.fetchone()
#打印
print('database version:%s'%data)
#事务提交
conn.commit()
#关闭数据库连接
conn.close()
#打印出数据库的版本说明数据库连接成功
#******创建表
import psycopg2
conn=psycopg2.connect(database='postgres',user='postgres',password='131415',host='127.0.0.1',port='5432')
cursor=conn.cursor()
sql="""CREATE TABLE STUDENT(
id serial PRIMARY KEY,
num INT4,
name VARCHAR(25));"""
cursor.execute(sql)
print("Create table student successfully!")
conn.commit()
conn.close()
#******插入操作
#插入数据形式1
import psycopg2
conn=psycopg2.connect(database='postgres',user='postgres',password='131415',host='127.0.0.1',port='5432')
cursor=conn.cursor()
sql="INSERT INTO student(num,name) VALUES (100,'lucy');"
cursor.execute(sql)
print("insert data successfully!")
conn.commit()
conn.close()
#插入数据形式2——参数分离
import psycopg2
conn=psycopg2.connect(database='postgres',user='postgres',password='131415',host='127.0.0.1',port='5432')
cursor=conn.cur