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 ...
随机推荐
- 从网上找的Android实用代码,记录备用
1.获取应用程序下所有Activity public static ArrayList<String> getActivities(Context ctx) { ArrayList< ...
- open jdk
http://rednaxelafx.iteye.com/blog/1549577 https://www.jianshu.com/p/f98c3acd8df8 http://download.jav ...
- 多线程本地图片载入演示样例【OpenCV】【Pthread】
Pthread barrier的简单使用演示样例: C++代码例如以下: // ThreadingLoadImages.cpp : 定义控制台应用程序的入口点. // #include "s ...
- java.lang.IllegalStateException——好头疼
在我东,下下来一个项目总会出现启动不了的问题,这些问题往往在编译的时候发现不了,当你的服务器启动的时候,就是一片片的报错,有些问题可以通过异常的提示信息,判断出来哪里配置错了,但是也有些情况下,从异常 ...
- js 学习
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta chars ...
- JPA+Hibernate 3.3 ——第一个JPA程序
所需要的最小的jar包(注意:jar包所在路径不能含有空格或中文) hibernate3.jarhibernate-cglib-repack-2.1_3.jarslf4j-api-1.5.2.jarj ...
- Nginx-rtmp 直播媒体实时流实现
0. 前言 这段时间在搭建一个IPCamera项目服务器.视频点对点通话,客户端会查看设备端的音视频实时流.为了省流量,是通过P2P进行穿透.但是由于NAT设备的原因和IPV4的枯竭.有些设备是无法进 ...
- vue条件与循环
通过vue控制切换一个元素的显示也相当简单: <div id="app-3"> <p v-if="seen">Now you see m ...
- 【消息】Pivotal Pivots 开源大数据处理的核心组件
Pivotal Pivots 开源大数据处理的核心组件 Pivotal 今天宣布将其大数据套件的三个核心组件开源,同时商业版本继续提供更高级特性和商业支持服务. 这三个开源的组件分别是: GemFir ...
- Python_序列与映射的解包操作
解包就是把序列或映射中每个元素单独提取出来,序列解包的一种简单用法就是把首个或前几个元素与后面几个元素分别提取出来,例如: first, seconde, *rest = sequence 如果seq ...