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 ...
随机推荐
- Linux终端记录神器
我们在调试程序的时候,免不了要去抓一些 log ,然后进行分析.如果 log 量不是很大的话,那很简单,只需简单的复制粘贴就好.但是如果做一些压力测试,产生大量 log ,而且系统内存又比较小(比如嵌 ...
- oracle 11g 安装及netca,dbca乱码之解决
在中文Linux下安装Oracle 11g,运行runInstaller后默认会出现乱码,解决办法如下: 1.准备字体zysong.ttf,点击下载,解压下载到的fallback 2.使用归档管理器打 ...
- 迁移ORACLE_HOME引发的登录sqlplus无法加载类库错误
在10g以后,一般情况下环境变量中没有必要设置LD_LIBRARY_PATH,但是一旦将ORACLE_HOME迁移到其他目录,则环境变量中还需要添加这个变量. Linux和Unix支持TAR方式迁移O ...
- orocos_kdl学习(一):坐标系变换
KDL中提供了点(point).坐标系(frame).刚体速度(twist),以及6维力/力矩(wrench)等基本几何元素,具体可以参考 Geometric primitives 文档. Creat ...
- 下载fiddler证书并设置信任
一.苹果手机 待整理 二.android手机 待整理
- 启用phpstorm代码提示功能
参考:http://www.dawnfly.cn/article-1-331.html mac下实际上将省电禁用即可
- 【编码题篇】收集整理来自网络上的一些常见的 经典前端、H5面试题 Web前端开发面试题
编写一个方法 求一个字符串的字节长度假设:一个英文字符占用一个字节,一个中文字符占用两个字节 function GetBytes(str){ var len = str.length; var byt ...
- 12C新特性--Application Continuity
Application Continuity特性可以在中断后恢复受影响的数据库会话的任务,从而让终端用户和应用程序感觉不到中断的发生.Application Continuity执行恢复的过程是在应用 ...
- cocos2d-x与UIKit混合编程实现半透明效果
关键词 cocos2d-x, UIKit, transparent 问题 cocos2d-x使用一个专门的OpenGL View进行渲染, 它的渲染和UIKit是分开进行的, 因此我们使用时一般是把c ...
- 【Spark 深入学习 07】RDD编程之旅基础篇03-键值对RDD
--------------------- 本节内容: · 键值对RDD出现背景 · 键值对RDD转化操作实例 · 键值对RDD行动操作实例 · 键值对RDD数据分区 · 参考资料 --------- ...