Python 操作 MySQL数据库
作者:RF-Dev 发布时间:2024-01-17 17:46:17
开发环境与配置
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)
来源:https://www.cnblogs.com/rustfisher/p/11750394.html


猜你喜欢
- Golang可以通过断言,判断值的类型s:="hello world"i:=interface{}(s)//将数值转化为
- 代码如下:import os, glob, timedef search_all_files_return_by_time_reversed
- 本文为大家分享了使用navicat将csv文件导入mysql的具体代码,供大家参考,具体内容如下1.打开navicat,连接到数据库并找到自
- 本文实例讲述了Python迭代器定义与简单用法。分享给大家供大家参考,具体如下:一、什么是迭代器迭代,顾名思义就是重复做一些事很多次(就现在
- 1. 信号与槽(Signals and slots)信号与槽机制是 PyQt 的核心机制,用于对象之间的通信,也就是实现函数之间的自动调用。
- Python中的字符串方法是从python1.6到2.0慢慢加进来的,它们也被加到了Jython中。这些方法实现了string模块的大部分方
- 昨天发现程序中数据分析的结果不对,重新进行分析后,原数据仍在,有值的字段被累计。心说,不对啊,是重新生成记录后才分析的啊。难道忘了DELET
- 本文实例讲述了Python使用matplotlib实现的图像读取、切割裁剪功能。分享给大家供大家参考,具体如下:# -*- coding:u
- 首先来看看这个php字符串替换函数 strtr()的两种用法:strtr(string,from,to) 或者strtr(string,ar
- 代码之余,将代码过程重要的一些代码段备份一下,如下的代码内容是关于Python从ftp服务器下载文件的的代码,希望能对小伙伴有用途。#cod
- 使用re, urllib, threading多线程抓取天涯帖子内容,设置url为需抓取的天涯帖子的第一页,设置file_name为下载后的
- 一.基本概念事务是指满足ACID特性的的一组操作,可以通过Commit提交事务,也可以也可以通过Rollback进行回滚。会存在中间态和一致
- 导语哈喽吖铁汁萌!今天这期就给大家介绍几个我用到的办公室自动化技巧,可以瞬速提高办公效率。有需要的可以往下滑了1、Word文档doc转doc
- 解决方法一: mysql安装时候的编码, 看下my.ini,有无 [mysql] default-character-set=utf8 [c
- var obj=document.getElementById("txtUserID") var range=obj.c
- 本文实例讲述了Python 函数用法。分享给大家供大家参考,具体如下:demo.py(函数定义):# say_hello() # 不能在定义
- 一、ready函数的实现经常用jQuery类库或其他类库中的ready方法,有时候想想它们到底是怎么实现的,但是看了一下jQuery中的源码
- 安装顺序rpm -ivhmysql-community-common-5.7.18-1.el7.x86_64.rpmmysql-commun
- $(function(){ var handler = function(){ } var timer = setInterval( han
- df.fillna主要用来对缺失值进行填充,可以选择填充具体的数字,或者选择临近填充。官方文档DataFrame.fillna(self,