import pymysql
def op_mysql(mysql_info:dir,sql:str,all=True)-> list:#list 表示返回值的类型
connect=pymysql.connect(**mysql_info)
cursor=connect.cursor()
cursor.execute(sql)
result=None
if sql.strip().lower().startswith("select"):
if all:
result=cursor.fetchall()
else:
result=cursor.fetchone()
# else:
# result=None
cursor.close()
connect.close()
return result
if __name__ == '__main__':
mysql_info={"host":"132.145.93.63","user":"jxz","password":"123456","port":3306,"db":"jxz","autocommit":True,"charset":"utf8"}
result=op_mysql(mysql_info,"select * from fmz;")
print(result)
------------------------------------------------------------------------------------------------------------------------------------------
import pymysql
# 132.145.93.63 jxz 123456
ip="132.145.93.63"
user="jxz"
pwd="123456"#必须是字符串
db="jxz"
port=3306#必须是int类型
connect=pymysql.connect(host=ip,user=user,password=pwd,db=db,port=port,charset="utf8")
#connect=pymysql.connect(host=ip,user=user,password=pwd,db=db,port=port,autocommit=True)autocommit=True 自动提交
#cursor=connect.cursor()#游标,仓库管理员,类似文件指针
cursor=connect.cursor(pymysql.cursors.DictCursor)#返回的是个字典
print(cursor.description)#获取表里面字段的描述
#sql="show tables;"
#sql="create table fmz(id int primary key atuo_increment, name varchar(50) not null,sex int default 0,phone varchar(11) unique)"
sql="select * from fmz;"
#sql1="insert into fmz (name,phone) values('张三','123452')"
#sql2="update fmz set phone=12311 where id =43"
#cursor.execute(sql1)#执行sql语句
#cursor.execute(sql2)#执行sql语句
cursor.execute(sql)#执行sql语句
#result=cursor.fetchall()#返回的是个二维数组
result2=cursor.fetchone()#只取一条
result1=cursor.fetchmany(5)#获取n条
connect.commit()#提交,才能到数据库
#connect.rollback()#回滚
#cursor.fetchone()
#print(result)
print(result2)
print(result1)
#如果数据量比较大的时候,可以循环游标
for c in cursor:#直接循环游标,每次取的就是表李敏的每一条数据
print(c)
cursor.close()#游标关闭
connect.close()#链接关闭