Python 操作 MySQL数据库


Posted in Python onSeptember 18, 2020

开发环境与配置

  • win_x64
  • Ubuntu14.04
  • Python3.x

pip安装pymysql模块

直接使用pip安装 pip install pymysql
win64上直接在cmd中执行

连接本地数据库

使用模块pymysql连接数据库

本地数据库相关配置请参阅: http://rustfisher.github.io/2017/02/25/backend/MySQL_install/

#!/usr/bin/python
# coding=utf-8
import pymysql

# 连接本地数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='yourpwd', db='samp_db1', charset='utf8')
cursor = conn.cursor()
cursor.execute('select * from bigstu')
for row in cursor.fetchall():
  print(row)

# 查
cursor.execute('select id, name from bigstu where age > 22')
for res in cursor.fetchall():
  print(str(res[0]) + ", " + res[1])

cursor.close()
print('-- end --')

输出:

(1, '张三', '男', 24, datetime.date(2017, 3, 29), '13666665555')
(6, '小刚', '男', 23, datetime.date(2017, 3, 11), '778899888')
(8, '小霞', '女', 20, datetime.date(2017, 3, 13), '13712345678')
(12, '小智', '男', 21, datetime.date(2017, 3, 7), '13787654321')
1, 张三
6, 小刚
-- end --

可以直接执行sql语句。获得的结果是元组。

sql相似条件查询

SELECT * FROM anindex.subject_basic_table where season_id having '2018';

插入数据

插入一条数据,接上面的代码

insertSql = "insert into bigstu (name, sex, age, mobile) values ('%s','%s',%d,'%s') "
xiuji = ('秀吉', '男', 15, '13400001111')
cursor.execute(insertSql % xiuji)
conn.commit() # 别忘了提交

添加列

在mobile后面添加一列cash

addCo = "alter table bigstu add cash int after mobile"
cursor.execute(addCo)

如果要设置默认值

addCo = "alter table bigstu add cash int default 0 after mobile"
cursor.execute(addCo)

删除数据

删除 name=秀吉 的数据

deleteSql = "delete from bigstu where name = '%s'"
cursor.execute(deleteSql % '秀吉')

删除列

删除cash列

dropCo = "alter table bigstu drop cash"
cursor.execute(dropCo)

修改数据

更新符合条件的数据

updateSql = "update bigstu set sex = '%s' where name = '%s'"
updateXiuji = ('秀吉', '秀吉') # 秀吉的性别是秀吉
cursor.execute(updateSql % updateXiuji)
conn.commit()

事物处理

给某个记录的cash增加

table = "bigstu"
addCash = "update " + table + " set cash = cash + '%d' where name = '%s'"
lucky = (1000, "秀吉")

try:
  cursor.execute(addCash % lucky)
except Exception as e:
  conn.rollback()
  print("加钱失败了")
else:
  conn.commit()

直接执行SQL语句,十分方便

代码片段

给数据库添加列

从json中读取需要添加的列名,获取当前2个表中所有的列名
整理得出需要插入的列名,然后将列插入到相应的表中

import pymysql
import json
import os
import secureUtils

mapping_keys = json.load(open("key_mapping_db.json", "r"))
db_keys = [] # json中所有的key

for k in mapping_keys.values():
  db_keys.append(k)

conn = pymysql.connect(host='localhost', port=3306, user='root',
            passwd='*****', db='db_name', charset='utf8')

cursor = conn.cursor()
table_main = "table_main"
main_table_keys = [] # 主表的列名
cursor.execute("show columns from " + table_main)
for row in cursor.fetchall():
  main_table_keys.append(row[0])

staff_table_keys = []
cursor.execute("show columns from table_second")
for row in cursor.fetchall():
  staff_table_keys.append(row[0])

need_to_insert_keys = []
for k in db_keys:
  if k not in staff_table_keys and k not in main_table_keys and k not in need_to_insert_keys:
    need_to_insert_keys.append(k)

print("need to insert " + str(len(need_to_insert_keys)))
print(need_to_insert_keys)
for kn in need_to_insert_keys:
  print("add key to db " + kn)
  cursor.execute("alter table staff_table add " + kn +" text")

conn.close()

将字段字符改变

这里将main_table_keys中的所有字段改为utf8

# change column character set to utf8
for co in main_table_keys:
  change_sql = "alter table " + table_main + " modify " + co + " text character set utf8"
  print(change_sql)
  cursor.execute(change_sql)

以上就是Python 如何操作 MySQL的详细内容,更多关于Python 操作 MySQL的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python益智游戏计算汉诺塔问题示例
Mar 05 Python
python中使用urllib2伪造HTTP报头的2个方法
Jul 07 Python
Python编写电话薄实现增删改查功能
May 07 Python
python3批量删除豆瓣分组下的好友的实现代码
Jun 07 Python
从零开始学Python第八周:详解网络编程基础(socket)
Dec 14 Python
TensorFlow实现创建分类器
Feb 06 Python
Django学习之文件上传与下载
Oct 06 Python
根据tensor的名字获取变量的值方式
Jan 04 Python
Python如何实现定时器功能
May 28 Python
Python连接HDFS实现文件上传下载及Pandas转换文本文件到CSV操作
Jun 06 Python
Python带参数的装饰器运行原理解析
Jun 09 Python
python Matplotlib模块的使用
Sep 16 Python
python实现人工蜂群算法
Sep 18 #Python
Python猫眼电影最近上映的电影票房信息
Sep 18 #Python
python实现简单遗传算法
Sep 18 #Python
详解python 支持向量机(SVM)算法
Sep 18 #Python
python利用线程实现多任务
Sep 18 #Python
Pycharm的Available Packages为空的解决方法
Sep 18 #Python
Pycharm Available Package无法显示/安装包的问题Error Loading Package List解决
Sep 18 #Python
You might like
PHP中判断文件存在使用is_file还是file_exists?
2015/04/03 PHP
超强多功能php绿色集成环境详解
2017/01/25 PHP
ThinkPHP 3.2.2实现事务操作的方法
2017/05/05 PHP
php实现支持中文的文件下载功能示例
2017/08/30 PHP
PHP实现动态压缩js与css文件的方法
2018/05/02 PHP
js 操作select相关方法函数
2009/12/06 Javascript
jquery随机展示头像代码
2011/12/21 Javascript
JQuery勾选指定name的复选框集合并显示的方法
2015/05/18 Javascript
javascript断点调试心得分享
2016/04/23 Javascript
基于jQuery的AJAX和JSON实现纯html数据模板
2016/08/09 Javascript
JS验证input输入框(字母,数字,符号,中文)
2017/03/23 Javascript
详解nodejs微信公众号开发——1.接入微信公众号
2017/04/10 NodeJs
Node.js应用设置安全的沙箱环境
2018/04/23 Javascript
微信小程序按钮去除边框线分享页面功能
2018/08/27 Javascript
Vue 实现一个命令式弹窗组件功能
2019/09/25 Javascript
JavaScript 生成唯一ID的几种方式
2021/02/19 Javascript
[05:05]DOTA2亚洲邀请赛 战队出场仪式
2015/02/07 DOTA
Python字符遍历的艺术
2008/09/06 Python
Python程序设计入门(4)模块和包
2014/06/16 Python
python友情链接检查方法
2015/07/08 Python
Python 多进程和数据传递的理解
2017/10/09 Python
pyhanlp安装介绍和简单应用
2019/02/22 Python
python制作填词游戏步骤详解
2019/05/05 Python
使用Python函数进行模块化的实现
2019/11/15 Python
Pytorch中的自动求梯度机制和Variable类实例
2020/02/29 Python
Scrapy框架介绍之Puppeteer渲染的使用
2020/06/19 Python
突袭HTML5之Javascript API扩展5—其他扩展(应用缓存/服务端消息/桌面通知)
2013/01/31 HTML / CSS
捷克领先的户外服装及配件市场零售商:ALPINE PRO
2018/01/09 全球购物
TobyDeals美国:在电子产品上获得最好的优惠和折扣
2019/08/11 全球购物
普通PHP程序员笔试题
2016/01/01 面试题
汽车技术服务英文求职信范文
2014/01/02 职场文书
初婚初育证明
2014/01/14 职场文书
合作经营协议书范本
2014/04/17 职场文书
2015初中教导处工作总结
2015/07/21 职场文书
毕业晚宴祝酒词
2015/08/11 职场文书
Nginx反向代理、重定向
2022/04/13 Servers