• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
bobo-tester
博客园    首页    新随笔    联系   管理    订阅  订阅

python操作mysql数据库

import pymysql

python操作mysql的一个过程:

#1、连上数据库 账号、密码 ip 端口号 数据库
#2、建立游标
#3、执行sql
#4、获取结果
#5、关闭游标
#6、连接关闭

代码如下:

1、执行查询的操作
coon = pymysql.connect(host='XXX.XX.X.XX',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8')

#port必须写int类型,
#charset这里必须写utf8

cur = coon.cursor() #建立游标
cur.execute('select * from stu;')#执行sql语句
res = cur.fetchall() #获取所有返回的结果
print(res)
cur.close() #关闭游标
coon.close() #关闭连接


代码如下:
1、执行插入的操作

coon = pymysql.connect(
host='xxx.xx.xx.xxx',user='jxz',passwd='123456',
port=3306,db='jxz',charset='utf8'
#port必须写int类型,
#charset这里必须写utf8
)
cur = coon.cursor() #建立游标
cur.execute('insert into stu (id,name,sex) VALUE (1,"username","女");')
# 在mysql中使用删除 delete 更新 update 插入 insert,必须执行coomit,否则不生效。
coon.commit() #必须得coomit
res = cur.fetchall() #获取所有返回的结果
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':
res = cur.fetchall()
else:
coon.commit()
res = 'ok'
cur.close()
coon.close()
return res

调用该方法:
res= my_db(host='118.24.3.40',user='jxz',passwd='123456',

db='jxz',port=3306,charset='utf8',sql="select * from stu; ")
print(res)
 
posted @ 2018-04-24 13:04  bobo-tester  阅读(161)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3