操作mysql
import pymysql #连接数据库,建立游标,执行sql语句,获取数据,关闭游标关闭连接 #连接数据库 conn = pymysql.connect(host='127.0.0.1', port=3306,user='jxz',password='123456', db='jxz',charset='utf8', autocommit=True)#加上autocommit参数就会自已提交 # cur = conn.cursor()#建立游标,结果返回元组 cur = conn.cursor(pymysql.cursors.DictCursor)#建立游标,结果返回字典 sql = "select * from app_myuser limit 5;" cur.execute(sql)#执行sql语句 result = cur.fetchone()#只获取一条数据,一维数组 result = cur.fetchall()#获取所有数据,二维数组 print(result) cur.close()#关闭游标 conn.close()#关闭连接 #连接数据库,并执行sql语句的函数 def op_mysql(info,sql:str): result = '执行完成' conn = pymysql.connect(**info)#建立连接 cur = conn.cursor(pymysql.cursors.DictCursor)#建立游标 cur.execute(sql)#执行sql if sql.strip().lower().startswith('select'): result = cur.fetchall()#返回查询结果 cur.close() conn.close() return result info = {'host':'127.0.07', 'port':3306,'user':'jxz', 'password':'123456','db':'jxz', 'charset':'utf8','autocommit':True} result = op_mysql(info,'select * from app_myuser limit 5') print(result)