操作 MySQL

mac2022-06-30  120

import pymysql

# 1、连上数据库 账号、密码 ip 端口号 数据库

#2、建立游标

#3、执行sql

#4 、获取结果

# 5、关闭游标

#6、连接关闭

coon = pymysql.connect(             host='xxx.xxx.xxx.xxx',user='xxxx',passwd='xxxxxx',             port=3306,db='jxz',charset='utf8'             #port必须写int类型,             #charset这里必须写utf8)   #连接数据库

cur = coon.cursor()   #建立游标

# cur.execute('select * from stu;')  #执行sql语句

cur.execute('insert into stu (id,name,sex) VALUE (1,"lynn","女");')# delete update insert

coon.commit()    #必须得coomit(除查询select 语句)

res = cur.fetchall()    #获取所有返回的结果(查询select 语句需要)

print(res)

cur.close()  #关闭游标

coon.close()  #关闭连接

例:封装一个数据库函数

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': #select、Select、SELECT 等都可以,所以要进行转换判断     res = cur.fetchall()   else:     coon.commit()   res = 'ok'   cur.close()   coon.close()   return res

转载于:https://www.cnblogs.com/lynn-chen/p/8991962.html

最新回复(0)