Python操作使用MySQL数据库的实例代码


Posted in Python onMay 25, 2017

Python 操作 MySQL

配置

  1. win_64
  2. Ubuntu14.04
  3. Python3.x

pip安装pymysql模块

直接使用pip安装 pip install pymysql

win64上直接在cmd中执行

连接本地数据库

使用模块pymysql连接数据库

#!/usr/bin/python
# coding=utf-8
import pymysql
# 连接本地数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='a123', 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语句。获得的结果是元组。

插入数据

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

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 相关文章推荐
python 随机数生成的代码的详细分析
May 15 Python
用Python代码来解图片迷宫的方法整理
Apr 02 Python
使用Python对Excel进行读写操作
Mar 30 Python
pygame 精灵的行走及二段跳的实现方法(必看篇)
Jul 10 Python
selenium python浏览器多窗口处理代码示例
Jan 15 Python
详解Python之unittest单元测试代码
Jan 24 Python
python实现微信发送邮件关闭电脑功能
Feb 22 Python
详解Python requests 超时和重试的方法
Dec 18 Python
python面向对象 反射原理解析
Aug 12 Python
PYTHON EVAL的用法及注意事项解析
Sep 06 Python
Python 获取项目根路径的代码
Sep 27 Python
python装饰器代替set get方法实例
Dec 19 Python
python爬虫入门教程--快速理解HTTP协议(一)
May 25 #Python
用生成器来改写直接返回列表的函数方法
May 25 #Python
Python随机读取文件实现实例
May 25 #Python
利用Anaconda完美解决Python 2与python 3的共存问题
May 25 #Python
Python实现的简单dns查询功能示例
May 24 #Python
Python向日志输出中添加上下文信息
May 24 #Python
Python常见加密模块用法分析【MD5,sha,crypt模块】
May 24 #Python
You might like
YII2框架中actions的作用与使用方法示例
2020/03/13 PHP
php中使用array_filter()函数过滤数组实例讲解
2021/03/03 PHP
Javascript中找到子元素在父元素内相对位置的代码
2012/07/21 Javascript
20行代码实现的一个CSS覆盖率测试脚本
2013/07/07 Javascript
Javascript原型链和原型的一个误区
2014/10/22 Javascript
jquery拖拽排序简单实现方法(效果增强版)
2016/02/16 Javascript
详细讲解JavaScript中的this绑定
2016/10/10 Javascript
jquery实现点击页面回到顶部
2016/11/23 Javascript
js仿iphone秒表功能 计算平均数
2017/01/11 Javascript
js实现增加数字显示的环形进度条效果
2017/02/05 Javascript
jquery.rotate.js实现可选抽奖次数和中奖内容的转盘抽奖代码
2017/08/23 jQuery
Angular实现的日程表功能【可添加及隐藏显示内容】
2017/12/27 Javascript
浏览器调试动态js脚本的方法(图解)
2018/01/19 Javascript
vue.js或js实现中文A-Z排序的方法
2018/03/08 Javascript
vuejs项目打包之后的首屏加载优化及打包之后出现的问题
2018/04/01 Javascript
Layer弹出层动态获取数据的方法
2018/08/20 Javascript
在微信小程序中使用mqtt服务的方法
2019/12/13 Javascript
js实现全选和全不选功能
2020/07/28 Javascript
[01:29]2014DOTA2展望TI 剑指西雅图DK战队专访
2014/06/30 DOTA
python模拟登录百度代码分享(获取百度贴吧等级)
2013/12/27 Python
Python的迭代器和生成器
2015/07/29 Python
Python对列表中的各项进行关联详解
2017/08/15 Python
简单了解OpenCV是个什么东西
2017/11/10 Python
python+openCV利用摄像头实现人员活动检测
2019/06/22 Python
python django生成迁移文件的实例
2019/08/31 Python
python自动分箱,计算woe,iv的实例代码
2019/11/22 Python
python中pickle模块浅析
2020/12/29 Python
出门问问全球官方商城:Tichome音箱和TicWatch智能手表
2017/12/02 全球购物
金士达面试非笔试
2012/03/14 面试题
四风自我剖析材料
2014/09/30 职场文书
党员三严三实心得体会
2014/10/13 职场文书
入党积极分子十八届四中全会思想汇报
2014/10/23 职场文书
工作保证书怎么写
2015/02/28 职场文书
暑期工社会实践报告
2015/07/13 职场文书
干货:我将这样书写我的演讲稿!
2019/05/09 职场文书
教你用python实现12306余票查询
2021/06/30 Python