python3 的 mysql 简单操作
一、python 提供的 db 接口
pymysql
两个基本对象: connection、cursor
连接示例
# connect_demo.py import pymysql db = pymysql.connect('localhost', 'root', 'root', 'imooc', charset='utf8')
cursor = db.cursor() print(db)
print(cursor) cursor.close()
db.close()
输出
<pymysql.connections.Connection object at 0x7f1e2a852278>
<pymysql.cursors.Cursor object at 0x7f1e2880e668>
操作游标
# cursor_demo.py import pymysql db = pymysql.connect('localhost', 'root', 'root', 'imooc', charset='utf8')
cursor = db.cursor() sql = 'select * from user' cursor.execute(sql) print(cursor.rowcount) result = cursor.fetchall()
print(result) for row in result:
print(row[0],':', row[1]) cursor.close()
db.close()
输出
((, 'lisi'), (, 'zhangsan'), (, 'liuqi'), (, 'white'))
: lisi
: zhangsan
: liuqi
: white
二、增删改查
# curd_demo.py import pymysql db = pymysql.connect('localhost', 'root', 'root', 'imooc', charset='utf8')
cursor = db.cursor() sql_select = "select * from user"
sql_insert = "insert into user(userid, username) values(DEFAULT, 'wuliu')"
sql_update = "update user set username='liuqi' where userid=3"
sql_delete = "delete from user where userid>4" cursor.execute(sql_select)
result = cursor.fetchall()
print(result) try:
cursor.execute(sql_insert)
result = cursor.rowcount
print(result) cursor.execute(sql_update)
result = cursor.rowcount
print(result) cursor.execute(sql_delete)
result = cursor.rowcount
print(result) db.commit()
except Exception as e:
print(e)
db.rollback() cursor.close()
db.close()
输出
((, 'lisi'), (, 'zhangsan'), (, 'liuqi'), (, 'white'))
三、事务的小示例
# bank_demo.py # coding:utf8 import sys
import pymysql class TransferMoney(object):
def __init__(self, conn):
self.conn = conn def check_acct_available(self, acctid):
cursor = self.conn.cursor()
try:
sql = "select * from account where acctid=%s" % acctid
cursor.execute(sql)
print("check_acct_available:" + sql)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("账号不存在" % acctid)
finally:
cursor.close() def has_enough_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "select * from account where acctid=%s and money>%s" % (acctid, money)
cursor.execute(sql)
print("chas_enough_mone:" + sql)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("账号%s余额不足" % acctid)
finally:
cursor.close() def reduce_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "update account set money=money - %s where acctid=%s" % (money, acctid)
cursor.execute(sql)
print("reduce_money:" + sql)
if cursor.rowcount != 1:
raise Exception("账号%s减款失败" % acctid)
finally:
cursor.close() def add_money(self, acctid, money):
cursor = self.conn.cursor()
try:
sql = "update account set money=money + %s where acctid=%s" % (money, acctid)
cursor.execute(sql)
print("rad_money:" + sql)
if cursor.rowcount != 1:
raise Exception("账号%s加款失败" % acctid)
finally:
cursor.close() def transfer(self, source_acctid, target_acctid, money):
try:
self.check_acct_available(source_acctid)
self.check_acct_available(target_acctid)
self.has_enough_money(source_acctid, money)
self.reduce_money(source_acctid, money)
self.add_money(target_acctid, money)
self.conn.commit()
except Exception as e:
self.conn.rollback()
raise e if __name__ == "__main__":
source_acctid= sys.argv[1]
target_acctid= sys.argv[2]
money = sys.argv[3] conn = pymysql.connect('localhost', 'root', 'root', 'imooc', charset='utf8')
tr_money = TransferMoney(conn) try:
tr_money.transfer(source_acctid, target_acctid, money)
except Exception as e:
print("出现问题:", str(e))
finally:
conn.close()
命令行运行
python bank_demo.py 3 1 1000
输出
check_acct_available:select * from account where acctid=
check_acct_available:select * from account where acctid=
chas_enough_mone:select * from account where acctid= and money>
reduce_money:update account set money=money - where acctid=
rad_money:update account set money=money + where acctid=
python3 的 mysql 简单操作的更多相关文章
- python(pymysql)之mysql简单操作
一.mysql简单介绍 说到数据库,我们大多想到的是关系型数据库,比如mysql.oracle.sqlserver等等,这些数据库软件在windows上安装都非常的方便,在Linux上如果要安装数据库 ...
- Linux下的MySQL简单操作(服务启动与关闭、启动与关闭、查看版本)
小弟今天记录一下在Linux系统下面的MySQL的简单使用,如下: 服务启动与关闭 启动与关闭 查看版本 环境 Linux版本:centeros 6.6(下面演示),Ubuntu 12.04(参见文章 ...
- mysql简单操作一
MySQL的一些简单管理: 启动MySQL服务: sudo start mysql 停止MySQL服务: sudo stop mysql 修改 MySQL 的管理员密码: sudo mysqladmi ...
- mysql简单操作
1,mysql 唤醒数据库,mysql -uroot -p11221 2,创建一个数据库: CREATE DATABASE mldn CHARACTER SET UTF8; 也可以写成小写的:crea ...
- mysql简单操作(实时更新)
从表中删除某条记录: delete from table_name where xx=xxxx; 创建数据库(注意不同系统对大小写的敏感性): create database xxx; 查看数据库列表 ...
- Linux上SQL及MYSQL简单操作
Linux上检查MYSQL是否安装: $ sudo service mysql start Ubuntu Linux安装配置MYSQL: $ sudo apt-get install mysql-se ...
- Node js MySQL简单操作
//win7环境下node要先安装MySQL的相关组件(非安装MySQL数据库),在cmd命令行进入node项目目录后执行以下语句 //npm install mysql var mysql = re ...
- mySQL简单操作(三)
1.事务 (1)ACID 原子性(不可分割性)automicity 一致性 consistency 隔离性 isolation 持久性 durability (2)事务控制语句 begin/start ...
- mySQL简单操作(二)
1.like子句 [where clause like '%com'] '%' '_' 2.正则 3.union操作符 用于连接多个select语句,[distinct]删除重复数据 select c ...
随机推荐
- SpringBoot集成Redis分布式锁以及Redis缓存
https://blog.csdn.net/qq_26525215/article/details/79182687 集成Redis 首先在pom.xml中加入需要的redis依赖和缓存依赖 < ...
- [Python设计模式] 第10章 怎么出试卷?——模版方法模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 小时候数学老师的随堂测验,都是老师在黑板上写题目,学生在下边抄,然后再做题 ...
- MySQL中的insert ignore into, replace into用法总结
MySQL replace into 有三种形式: 1. replace into tbl_name(col_name, ...) values(...) 2. replace into tbl_na ...
- How to extract a complete list of extension types within a directory?
Open the PowerShell Tool and Run the below command: Get-Childitem "D:\testfolder\" -Recurs ...
- Window下对nodejs多版本管理GNVM
Windows下对nodejs多版本的管理,实现随意切换! 官方地址: https://github.com/Kenshin/gnvm http://ksria.com/gnvm/ 01.下载GNVM ...
- Benchmark Web App 性能瓶颈分析与性能测试工具的使用方法总结
主要分为以下几个要素的指标: Disk IO . CPU . mem . Net . MySQL Web性能测试工具: 客户端 服务器端: 服务器性能测试工具: 服务器性能瓶颈分析工具: ab, si ...
- 电子证书 DER & PEM & CRT & CER
原文链接: http://blog.csdn.net/zqt520/article/details/26966603 证书与编码 本至上,X.509证书是一个数字文档,这个文档根据RFC 5280来编 ...
- Android UI系列-----LinearLayout的综合使用
这里将会对LinearLayout的布局方式进行一个综合的使用,通过一个例子来看看LinearLayout的嵌套布局方式,在这之前首先介绍三个属性: 1.①android:layout_weigth: ...
- SNF快速开发平台3.0之BS页面展示和九大优点-部分页面显示效果-Asp.net+MVC4.0+WebAPI+EasyUI+Knockout
一)经过多年的实践不断优化.精心维护.运行稳定.功能完善: 能经得起不同实施策略下客户的折腾,能满足各种情况下客户的复杂需求. 二)编码实现简单易懂.符合设计模式等理念: 上手快,见效快.方便维护,能 ...
- Mac下不显示设备
使用命令行adb devices 试了下,没设备列表. 第一步: 查看usb设备信息 在 终端输入:system_profiler SPUSBDataType 可以查看连接的usb设备的信息 ...