快速上手python 操作Postgresql

2019-02-16  本文已影响0人  凌霄子

import psycopg2

conn=psycopg2.connect(database='postgres',user='postgres',password='1234',host='127.0.0.1',port='5432')

cur=conn.cursor()

#增

name="SSS"

age=23

cur.execute("insert into test_table(name,age) values(%s,%s)",(name,age))

cur.mommit()

#批量增

data=pd.DataFrame({'name':['xzi','xil','xiy'],

                  'age':[12,43,54]})

data=np.array(data) #转为list

sql="insert into test_table(name,age) values(%s,%s)"

cur.executemany(sql,data)

#改

name='xil'

cur.execute("update test_table set age=23 where name=%s",(name,))  #当个值时,括号后面要加逗号

#删

cur.execute('delete from test_table where age<=23')

#查

cur.execute('select * from test_table')

cur.fetchall() 获取全部

#cur.fetchone()

#建表

cursor.execute('''create table public.member(

id integer not null primary key,

name varchar(32) not null,

password varchar(32) not null,

singal varchar(128)

)''')

conn.commit()

conn.close()

#conn.rollback()

#conn.commit()

上一篇 下一篇

猜你喜欢

热点阅读