Method of Python Operating PostgreSql Database of Basic Addition Deletion Modification and Search
- 2021-09-05 00:21:53
- OfStack
Python operation PostgreSql database (basic addition, deletion and modification)
Of course, the fastest way to operate the database is to use SQL language directly to operate the database, but occasionally we will encounter the situation of operating the database in the code. We may use ORM class library to operate the NC library, but when a large amount of data needs to be operated, ORM data is too slow. In python, in such a situation, I recommend using
psycopg2
Operation
postgresql
Database
psycopg2
Official document portal: http://initd.org/psycopg/docs/index. html
Simple addition, deletion and revision
Connect
Connect to pg and create a table
PG_SQL_LOCAL = {
'database': 'postgres',
'user': 'postgres',
'password': "8dsa581",
# 'host':'10.27.78.1',
'host': 'localhost'
}
def connectPostgreSQL():
conn = psycopg2.connect(**PG_SQL_LOCAL)
print('connect successful!')
cursor = conn.cursor()
cursor.execute('''
create table public.members(
id integer not null primary key,
name varchar(32) not null,
password varchar(32) not null,
singal varchar(128)
)''')
conn.commit()
conn.close()
print('table public.member is created!')
Increase
Added data of 1 article and 1 article
def insertOperate():
conn = psycopg2.connect(**PG_SQL_LOCAL)
cursor = conn.cursor()
cursor.execute("insert into public.member(id,name,password,singal)\
values(1,'member0','password0','signal0')")
cursor.execute("insert into public.member(id,name,password,singal)\
values(2,'member1','password1','signal1')")
cursor.execute("insert into public.member(id,name,password,singal)\
values(3,'member2','password2','signal2')")
cursor.execute("insert into public.member(id,name,password,singal)\
values(4,'member3','password3','signal3')")
row = conn.fetchone()
print(row)
conn.commit()
conn.close()
print('insert records into public.memmber successfully')
Check
fetchall () gets all data once fetchmany () Extracts 2000 pieces of data once (using server-side cursors)
def selectOperate():
conn = psycopg2.connect(**PG_SQL_LOCAL)
cursor = conn.cursor()
cursor.execute("select id,name,password,singal from public.member where id>2")
# rows = cursor.fetchall()
# for row in rows:
# print('id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3],)
while True:
rows = cursor.fetchmany(2000)
if not rows:
break
for row in rows:
# print('id=', row['id'], ',name=', row['name'], ',pwd=', row['pwd'], ',singal=', row['singal'],)
rid,name,pwd,singal = row
print(rid,name,pwd,singal)
# print('id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], )
conn.close()
Change
Update data
def updateOperate():
conn = psycopg2.connect(**PG_SQL_LOCAL)
cursor=conn.cursor()
result = cursor.execute("update public.member set name='member X' where id=3")
print(result)
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
cursor.execute("select id,name,password,singal from public.member")
rows=cursor.fetchall()
for row in rows:
print('id=',row[0], ',name=',row[1],',pwd=',row[2],',singal=',row[3],'\n')
conn.close()
Delete
Delete data
def deleteOperate():
conn = psycopg2.connect(**PG_SQL_LOCAL)
cursor = conn.cursor()
cursor.execute("select id,name,password,singal from public.member")
rows = cursor.fetchall()
for row in rows:
print('id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n')
print('begin delete')
cursor.execute("delete from public.member where id=2")
conn.commit()
print('end delete')
print("Total number of rows deleted :", cursor.rowcount)
cursor.execute("select id,name,password,singal from public.member")
rows = cursor.fetchall()
for row in rows:
print('id=', row[0], ',name=', row[1], ',pwd=', row[2], ',singal=', row[3], '\n')
conn.close()
Added, added fields with time format
With time format, you only need to pass in the string in time format ('2017-05-27'), which will be automatically recognized by PG
cur.execute("INSERT INTO Employee "
"VALUES('Gopher', 'China Beijing', 100, '2017-05-27')")
# Query data
cur.execute("SELECT * FROM Employee")
rows = cur.fetchall()
for row in rows:
print('name=' + str(row[0]) + ' address=' + str(row[1]) +
' age=' + str(row[2]) + ' date=' + str(row[3]), type(row[3]))
# Insert data
sql = """INSERT INTO Employees VALUES(%s, %s, %s,%s) """
var = []
var.append([row[0], row[1], row[2], row[3]])
cur.executemany(sql, var)
# Commit transaction
conn.commit()
# Close the connection
conn.close()