一、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 简单操作的更多相关文章

  1. python(pymysql)之mysql简单操作

    一.mysql简单介绍 说到数据库,我们大多想到的是关系型数据库,比如mysql.oracle.sqlserver等等,这些数据库软件在windows上安装都非常的方便,在Linux上如果要安装数据库 ...

  2. Linux下的MySQL简单操作(服务启动与关闭、启动与关闭、查看版本)

    小弟今天记录一下在Linux系统下面的MySQL的简单使用,如下: 服务启动与关闭 启动与关闭 查看版本 环境 Linux版本:centeros 6.6(下面演示),Ubuntu 12.04(参见文章 ...

  3. mysql简单操作一

    MySQL的一些简单管理: 启动MySQL服务: sudo start mysql 停止MySQL服务: sudo stop mysql 修改 MySQL 的管理员密码: sudo mysqladmi ...

  4. mysql简单操作

    1,mysql 唤醒数据库,mysql -uroot -p11221 2,创建一个数据库: CREATE DATABASE mldn CHARACTER SET UTF8; 也可以写成小写的:crea ...

  5. mysql简单操作(实时更新)

    从表中删除某条记录: delete from table_name where xx=xxxx; 创建数据库(注意不同系统对大小写的敏感性): create database xxx; 查看数据库列表 ...

  6. Linux上SQL及MYSQL简单操作

    Linux上检查MYSQL是否安装: $ sudo service mysql start Ubuntu Linux安装配置MYSQL: $ sudo apt-get install mysql-se ...

  7. Node js MySQL简单操作

    //win7环境下node要先安装MySQL的相关组件(非安装MySQL数据库),在cmd命令行进入node项目目录后执行以下语句 //npm install mysql var mysql = re ...

  8. mySQL简单操作(三)

    1.事务 (1)ACID 原子性(不可分割性)automicity 一致性 consistency 隔离性 isolation 持久性 durability (2)事务控制语句 begin/start ...

  9. mySQL简单操作(二)

    1.like子句 [where clause like '%com'] '%' '_' 2.正则 3.union操作符 用于连接多个select语句,[distinct]删除重复数据 select c ...

随机推荐

  1. docker-compose中启动镜像失败的问题

    http://blog.csdn.net/boling_cavalry/article/details/79050451 解决docker-compose启动镜像失败的问题: 原文地址:http:// ...

  2. redis-desktop-manager 的简单使用

    1:安装比较简单,所有软件几乎都一样(下载.安装)我就从安装好后,怎么玩记录吧!如下图,双击对应的图标就能打开此软件了 2-1:连接redis服务器的方式之一——导入对应的redis信息 连接配置的样 ...

  3. Apache Spark 2.2.0 新特性详细介绍

    本章内容: 待整理 参考文献: Apache Spark 2.2.0新特性详细介绍 Introducing Apache Spark 2.2

  4. logback配置详解

    本文转自:https://segmentfault.com/a/1190000008315137 概览 简单地说,Logback 是一个 Java 领域的日志框架.它被认为是 Log4J 的继承人.L ...

  5. 第一部分:开发前的准备-第八章 Android SDK与源码下载

    第8章 Android SDK与源码下载 如果你是新下载的SDK,请阅读一下步骤了解如何设置SDK.如果你已经下载使用过SDK,那么你应该使用AVD Manager,来更新即可. 下面是构建Andro ...

  6. 系统用户在Samba服务器中起一个别名

    (1)通过/etc/samba/smbusers文件设置用户映射关系 如实列: # cat /etc/samba/smbusers # Unix_name = SMB_name1 SMB_name2 ...

  7. SSH免登录及原理

    1.免登陆实现 1)在本机生成公钥/私钥对 ssh-keygen 执行成功后,在.ssh文件夹下,会多出两个文件 id_rsa和id_rsa.pub 2)将公钥写入远端服务器.ssh文件夹下的auth ...

  8. IOS开发之Core Location

    IOS 支持三种检测当前位置的方式:手机基站.Wi-Fi.和GPS,其中GPS是经度最高的,同时也是最耗费手机电量的.一般情况下在室内是无法通过GPS获 取位置信息的,通过Wi-Fi获取位置的原理是通 ...

  9. 安装polyglot出错

    安装polyglot出错 错误 Complete output from command python setup.py egg_info: Traceback (most recent call l ...

  10. js实现cookie跨域功能

    /** * 设置cookie方法 * @param {string} name cookie键值 * @return {*} 返回cookie值 */ function setCookie_log(c ...