Python操作数据库

import pymysql
# 端口默认3306int类型
#1、连接数据库 账号、密码、IP、端口号、数据库
#2、建立游标
#3、执行sql
#4、获取结果
#5、关闭游标
#6、关闭连接
conn=pymysql.connect(
host='xxx.xx.x.xx',user='xxx',passwd='123456',
port=3306,db='xxx',charset='utf8'#charset必须写utf8
)
cur=conn.cursor()#建立游标
# cur.execute('insert into stu (id,name,sex) VALUES(1,"小白","女");')#执行sql
# conn.commit()#除了查询都要提交
cur.execute("select * from stu")#
sql=cur.fetchall()#获取所有返回的结果
print(sql)
cur.close()#关闭游标
conn.close()#关闭连接


------操作数据库函数
def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
coon=pymysql.connect(user=user,passwd=passwd,host=host,port=port,db=db,charset=charset)
cur=coon.cursor()#建立游标
cur.execute(sql)#执行sql
if sql.strip()[0:6].upper()=='SELECT':
res=cur.fetchall()
else:
coon.commit()
res='ok'
cur.close()
coon.close()
return res

猜你喜欢

转载自www.cnblogs.com/irisx/p/8907815.html