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不需要commit
coon.commit() #必须得commit
res = cur.fetchall() #获取所有返回的结果
print(res)
cur.close()#关闭游标
coon.close()#关闭连接
print("================分隔代码块=============")
#https://www.cnblogs.com/tkqasn/p/6001134.html
def 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