Python operation database

import pymysql 
# port default 3306int type
#1, connect database account, password, IP, port number, database
#2, create cursor
#3, execute sql
#4, get result
#5, close cursor
#6, close connection
conn=pymysql .connect(
host='xxx.xx.x.xx',user='xxx',passwd='123456',
port=3306,db='xxx',charset='utf8'#charset must write utf8
)
cur= conn.cursor()#Create a cursor
# cur.execute('insert into stu (id,name,sex) VALUES(1,"Xiaobai","Female");')#Execute sql
# conn.commit()# In addition to the query, submit
cur.execute("select * from stu")#
sql=cur.fetchall()#Get all the returned results
print(sql)
cur.close()#Close the cursor
conn.close()#Close the connection


------Operate database functions
def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
coon=pymysql.connect(user=user,passwd=passwd,host=host,port=port,db=db,charset=charset)
cur=coon.cursor()#建立游标
cur.execute(sql)#执行sql
if sql.strip()[0:6].upper()=='SELECT':
res=cur.fetchall()
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324633708&siteId=291194637