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中操作列表之list.extend()方法的使用
May 20 Python
Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)
Sep 21 Python
使用PM2+nginx部署python项目的方法示例
Nov 07 Python
使用python 打开文件并做匹配处理的实例
Jan 02 Python
Django Channels 实现点对点实时聊天和消息推送功能
Jul 17 Python
python获取array中指定元素的示例
Nov 26 Python
python使用beautifulsoup4爬取酷狗音乐代码实例
Dec 04 Python
tensorflow之读取jpg图像长和宽实例
Jun 18 Python
Python configparser模块应用过程解析
Aug 14 Python
python将下载到本地m3u8视频合成MP4的代码详解
Nov 24 Python
在Python中实现字典反转案例
Dec 05 Python
PyTorch中的拷贝与就地操作详解
Dec 09 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 输出双引号"与单引号'的方法
2010/05/09 PHP
PHP遍历数组的几种方法
2012/03/22 PHP
探讨多键值cookie(php中cookie存取数组)的详解
2013/06/06 PHP
php 微信公众平台开发模式实现多客服的实例代码
2016/11/07 PHP
解决PHP使用CURL发送GET请求时传递参数的问题
2019/10/11 PHP
JS Timing
2007/04/21 Javascript
老鱼 浅谈javascript面向对象编程
2010/03/04 Javascript
jquery 查找select ,并触发事件的实现代码
2011/03/30 Javascript
js原型链原理看图说明
2012/07/07 Javascript
JS图片预加载 JS实现图片预加载应用
2012/12/03 Javascript
JS+flash实现chrome和ie浏览器下同时可以复制粘贴
2013/09/22 Javascript
jQuery+easyui中的combobox实现下拉框特效
2015/02/27 Javascript
PHP结合jQuery实现的评论顶、踩功能
2015/07/22 Javascript
JS获取和修改元素样式的实例代码
2016/08/06 Javascript
利用jQuery对无序列表排序的简单方法
2016/10/16 Javascript
jQuery+ajax实现动态添加表格tr td功能示例
2018/04/23 jQuery
Vuejs2 + Webpack框架里,模拟下载的实例讲解
2018/09/05 Javascript
[50:44]DOTA2-DPC中国联赛 正赛 SAG vs Dragon BO3 第二场 2月22日
2021/03/11 DOTA
python基础教程之Hello World!
2014/08/29 Python
Python中的字典遍历备忘
2015/01/17 Python
详解Django框架中用户的登录和退出的实现
2015/07/23 Python
Python实现截屏的函数
2015/07/26 Python
python3抓取中文网页的方法
2015/07/28 Python
python按行读取文件,去掉每行的换行符\n的实例
2018/04/19 Python
[原创]Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】
2018/10/29 Python
python rsa实现数据加密和解密、签名加密和验签功能
2019/09/18 Python
Python模块汇总(常用第三方库)
2019/10/07 Python
Jupyter打开图形界面并画出正弦函数图像实例
2020/04/24 Python
python编写实现抽奖器
2020/09/10 Python
python 窃取摄像头照片的实现示例
2021/01/08 Python
法国创作个性化T恤衫和其他定制产品平台:Tostadora
2018/04/08 全球购物
全球采购的街头服饰和帽子:Urban Excess
2020/10/28 全球购物
Perfume’s Club中文官网:西班牙美妆在线零售品牌
2020/08/24 全球购物
职称自我鉴定
2013/10/15 职场文书
2014年幼儿园元旦活动方案
2014/02/13 职场文书
2014年学校工会工作总结
2014/12/06 职场文书