Python【pymysql】模块

mac2022-06-30  63

import pymysql# 1、连上数据库 账号、密码 ip 端口号 数据库#2、建立游标#3、执行sql#4 、获取结果# 5、关闭游标#6、连接关闭coon = pymysql.connect( host='127.0.0.1',user='jxz',passwd='123456', port=3306,db='jxz',charset='utf8' #port必须写int类型, #charset这里必须写utf8,不能写utf-8,写utf-8会报错 #写成username是错误的,必须写成user)cur = coon.cursor() #建立游标# cur.execute('select * from stu;')#执行sql语句cur.execute('insert into stu (id,name,sex) VALUE (1,"牛寒阳","女");')# delete update insert必须commit,select不需要commitcoon.commit() #必须得commitres = cur.fetchall() #获取所有返回的结果print(res)cur.close()#关闭游标coon.close()#关闭连接print("================分隔代码块=============")#https://www.cnblogs.com/tkqasn/p/6001134.htmldef my_db(host,user,passwd,db,sql,port=3306,charset='utf8'): import pymysql coon = pymysql.connect(user=user, host=host, port=port, passwd=passwd, db=db, charset=charset ) cur = coon.cursor() #建立游标 cur.execute(sql)#执行sql if sql.strip()[:6].upper()=='SELECT': res = cur.fetchall() #返回的结果是一个二维元组 else: coon.commit() res = 'ok' cur.close() coon.close() return res

转载于:https://www.cnblogs.com/mtszw/p/9022047.html

相关资源:Python-pymysql模块
最新回复(0)