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 mysqldb连接数据库
Mar 16 Python
python实现的一个p2p文件传输实例
Jun 04 Python
详解Python中with语句的用法
Apr 15 Python
详解Python爬虫的基本写法
Jan 08 Python
python爬虫之自动登录与验证码识别
Jun 15 Python
python 多线程中子线程和主线程相互通信方法
Nov 09 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
python三引号输出方法
Feb 27 Python
浅谈Python小波分析库Pywavelets的一点使用心得
Jul 09 Python
djano一对一、多对多、分页实例代码
Aug 16 Python
Django 设置admin后台表和App(应用)为中文名的操作方法
May 10 Python
python邮件中附加文字、html、图片、附件实现方法
Jan 04 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
一个用mysql_odbc和php写的serach数据库程序
2006/10/09 PHP
PHP加密解密函数详解
2015/10/28 PHP
PHP 裁剪图片
2021/03/09 PHP
JavaScript中数组对象的那些自带方法介绍
2013/03/12 Javascript
jQuery选择器源码解读(八):addCombinator函数
2015/03/31 Javascript
AngularJs动态加载模块和依赖注入详解
2016/01/11 Javascript
js右下角弹出提示框示例代码
2016/01/12 Javascript
jquery文字填写自动高度的实现方法
2016/11/07 Javascript
Bootstrap Modal遮罩弹出层(完整版)
2016/11/21 Javascript
微信公众平台开发教程(六)获取个性二维码的实例
2016/12/02 Javascript
Bootstrap基本插件学习笔记之Tooltip提示工具(18)
2016/12/08 Javascript
jQuery网页定位导航特效实现方法
2016/12/19 Javascript
微信小程序 图片宽度自适应的实现
2017/04/06 Javascript
jquery实现图片轮播器
2017/05/23 jQuery
vue+iview写个弹框的示例代码
2017/12/05 Javascript
详解Require.js与Sea.js的区别
2018/08/05 Javascript
Javascript迭代、递推、穷举、递归常用算法实例讲解
2019/02/01 Javascript
Vue-CLI 3 scp2自动部署项目至服务器的方法
2020/07/24 Javascript
[40:53]完美世界DOTA2联赛PWL S3 Magma vs DLG 第二场 12.18
2020/12/20 DOTA
Python中lambda的用法及其与def的区别解析
2014/07/28 Python
Python实现正则表达式匹配任意的邮箱方法
2018/12/20 Python
python微信聊天机器人改进版(定时或触发抓取天气预报、励志语录等,向好友推送)
2019/04/25 Python
python打开使用的方法
2019/09/30 Python
Python Tkinter Entry和Text的添加与使用详解
2020/03/04 Python
python连接mysql有哪些方法
2020/06/24 Python
python 实现数据库中数据添加、查询与更新的示例代码
2020/12/07 Python
matplotlib自定义鼠标光标坐标格式的实现
2021/01/08 Python
黄色火烈鸟:De Gele Flamingo
2019/03/18 全球购物
古驰英国官网:GUCCI英国
2020/03/07 全球购物
某/etc/fstab文件中的某行如下: /dev/had5 /mnt/dosdata msdos defaults,usrquota 1 2 请解释其含义
2013/04/11 面试题
师范生教师实习自我鉴定
2013/09/27 职场文书
工商学院毕业生自荐信
2013/11/12 职场文书
中西医专业毕业生职业规划书
2014/02/24 职场文书
让子弹飞观后感
2015/06/11 职场文书
在校证明模板
2015/06/17 职场文书
幼儿园科学课教学反思
2016/03/03 职场文书