MySQLdb
MySQLdb设计实战
import MySQLdb
from DBUtils.PooledDB import PooledDB
pool = PooledDB(MySQLdb,5,host='localhost',user='root',passwd='pwd',db='myDB',port=3306,blocking=True) #5为连接池里的最少连接数 conn = pool.connection() #以后每次需要数据库连接就是用connection()函数获取连接就好了
cur=conn.cursor()
SQL="select * from table1"
r=cur.execute(SQL)
r=cur.fetchall()
cur.close()
conn.close() # 创建数据库
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS=0; #禁用外键约束
DROP TABLE IF EXISTS `employee_tbl`; CREATE TABLE IF NOT EXISTS `runoob_tbl`(
`runoob_id` INT UNSIGNED AUTO_INCREMENT NOT NULL,
`runoob_title` VARCHAR(100) NOT NULL UNIQUE,
`runoob_author` VARCHAR(40) NOT NULL,
`submission_date` DATETIME NOT NULL,
`sex` enum('m','w','l') DEFAULT NULL,
PRIMARY KEY ( `runoob_id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into runoob_tbl(runoob_title, runoob_author, submission_date) values("a", "b", now());
INSERT INTO runoob_tbl(runoob_title, runoob_author, submission_date) VALUES("JAVA 教程", "RUNOOB.COM", '2016-05-06');
UPDATE runoob_tbl SET runoob_title='a' WHERE runoob_id=1;
DELETE FROM runoob_tbl WHERE runoob_id=3;
SELECT * from runoob_tbl WHERE runoob_title LIKE '%a%';
SELECT country FROM Websites UNION ALL SELECT country FROM apps ORDER BY country; UNION ALL不会去重
SELECT * from runoob_tbl ORDER BY submission_date DESC; DESC升序,高的在上 AESC降序,高的在下
SELECT name FROM person_tbl WHERE name REGEXP 'ok$'; name字段中以'ok'为结尾
MySQLdb的使用
#mysql> create table `account`(
# -> `acctid` int(11) default null comment 'XXXX',
# -> `money` int(11) default null comment 'XXX'
# -> ) ENGINE = innodb default charset = utf8;
#coding:utf8
import sys
import MySQLdb class TransferMoney(object):
def __init__(self,conn):
self.conn = conn
def transfer(self,s,t,money):
try:
self.check_acct_avilable(s)
self.check_acct_avilable(t)
self.has_enough_money(s,money)
self.reduce_money(s,money)
self.add_money(t,money)
self.conn.commit()
except Exception as e:
self.conn.rollback()
raise e
def check_acct_avilable(self,acctid):
cursor = self.conn.cursor()
try:
cursor = self.conn.cursor()
sql = "select * from account where acctid=%s"%acctid
cursor.execute(sql)
print "check_acct_avilable: " + sql
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("not have this ID %s"%acctid)
finally:
cursor.close() def has_enough_money(self,acctid,money):
cursor = self.conn.cursor()
try:
cursor = self.conn.cursor()
sql = "select * from account where acctid=%s and money > %s"%(acctid,money)
cursor.execute(sql)
print "has_enough_money: " + sql
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception("accout not have enough money %s"%acctid)
finally:
cursor.close() def reduce_money(self,acctid,money):
cursor = self.conn.cursor()
try:
cursor = self.conn.cursor()
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("ID reduce money fail %s"%acctid)
finally:
cursor.close() def add_money(self,acctid,money):
cursor = self.conn.cursor()
try:
cursor = self.conn.cursor()
sql = "update account set money=money+%s where acctid=%s"%(money,acctid)
cursor.execute(sql)
print "add_money: " + sql
if cursor.rowcount != 1:
raise Exception("ID add money fail %s"%acctid)
finally:
cursor.close() if __name__ == "__main__":
s = sys.argv[1]
t = sys.argv[2]
money = sys.argv[3] conn = MySQLdb.Connect(host = '127.0.0.1',port = 3306,user = 'root',passwd = 'wjl123',db = 'imooc',charset = 'utf8')
t_m = TransferMoney(conn) try:
t_m.transfer(s,t,money)
except Exception as e:
print e
finally:
conn.close()
MySQLdb的更多相关文章
- ubuntu 启动MySql和安装python的MySQLdb模块
ubuntu一般会自己预安装mysql,你只需 /etc/init.d/mysql start|stop|restart|reload|force-reload|status 命令便可以实现mysq ...
- Mysql5.5升级到5.7后MySQLdb不能正常使用的问题解决
ubuntu系统 报错信息1 Type "help", "copyright", "credits" or "license&qu ...
- Python3.4下安装pip和MySQLdb
想用pyhton3.4做数据分析,pip和MySQLdb是必要的,一个便于安装常用模块,一个用来操作数据库.当时安装这两个模块时,由于没有人指导,花了很多的时间才安装好. 安装pip时,按照网上的教程 ...
- Create function through MySQLdb
http://stackoverflow.com/questions/745538/create-function-through-mysqldb How can I define a multi-s ...
- python MySQLdb 对mysql基本操作方法
#!/usr/bin/env python # -*- coding:utf-8 -*- import MySQLdb conn = MySQLdb.connect(host=',db='host') ...
- Python的MySQLdb模块安装
MySQL-python-1.2.1.tar.gz 下载地址:https://pan.baidu.com/s/1kVfH84v 然后解压,打开README(这个其实没有什么鸟用) 里面有安装过程: ...
- Python中MySQLdb模块的安装
安装 MySQLdb是Python语言访问mysql数据库的一个模块,如果你不确定自己的Python环境中是否已经安装了这个模块,可以打开Python shell,输入import MySQLdb,如 ...
- [Python] MySQLdb(即 MySQL-python 包)在 OS X 中安装指南
本文参考:http://www.cnblogs.com/ifantastic/archive/2013/04/13/3017677.html 安装环境:OS X 操作系统,Python 2.7.10 ...
- MySQLdb操作mysql的blob值
一般情况下我们是把图片存储在文件系统中,而只在数据库中存储文件路径的,但是有时候也会有特殊的需求:把图片二进制存入数据库. 今天我们采用的是python+mysql的方式 MYSQL 是支持把图片存入 ...
- mac OS X 配置Python+Web.py+MySQLdb环境
MAC默认支持Python 2.7所以不用安装. 1.安装pip sudo easy_install pip 2.安装Web.py sudo pip install Web.py 3.安装MySQLd ...
随机推荐
- 2016 - 1 - 19NSOpertation的依赖关系和监听
一:NSOperation的依赖: 1.概念:队列中的A操作需要等其他B操作或者某些操作执行完毕后才执行,就叫做A依赖与B或者A依赖于其他某些操作. 2.注意点:不能循环依赖,否则卡死.如: [op2 ...
- Chapter 1: A Simple Web Server
这算是一篇读书笔记,留着以后复习看看. Web Server又称为Http Server,因为它使用HTTP协议和客户端(一般是各种各样的浏览器)进行通信. 什么是HTTP协议呢? HTTP协议是基于 ...
- AmazeUI布局
AmazeUI使用了12列的响应式网络系统.使用时需在外围容器上添加.am-g class,在列上添加.am-u-[sm|md|lg]-[1-12] class,然后根据不同的屏幕需求设置不同的宽度. ...
- 关于linux python vim的一些基础知识(很零散)
清空文件夹filenmae下所有文件 rm filename/* vim复制大量代码段 num+yy 从光标起始处复制num个数行 然后 python: 设置中断 1.from IPython imp ...
- dll强签名的由来和作用
C# dll强签名介绍 之前基本没有这个概念,直到有一天我们的dll被反编译了,导致我们的代码基本上被看到了,才想起来要保护dll的安全性,因为C#语言的在编译过程中会产生中间语言导致dll很容易被反 ...
- Objective-C语言介绍 、 Objc与C语言 、 面向对象编程 、 类和对象 、 属性和方法 、 属性和实例变量
1 第一个OC控制台程序 1.1 问题 Xcode是苹果公司向开发人员提供的集成开发环境(非开源),用于开发Mac OS X,iOS的应用程序.其运行于苹果公司的Mac操作系统下. 本案例要求使用集成 ...
- 如何避免后台IO高负载造成的长时间JVM GC停顿(转)
译者著:其实本文的中心意思非常简单,没有耐心的读者建议直接拉到最后看结论部分,有兴趣的读者可以详细阅读一下. 原文发表于Linkedin Engineering,作者 Zhenyun Zhuang是L ...
- Windows服务弹出MessageBox对话框
Windows服务弹出MessageBox对话框 自从Windows升级到Vista版本后,系统服务就不在允许弹出那些惨绝人寰的MessageBox了(至于为什么不让弹出,原理有点小复杂,我也不是很门 ...
- Core Java Volume I — 3.10. Arrays
3.10. ArraysAn array is a data structure that stores a collection of values of the same type. You ac ...
- hadoop常用基础命令
1.日志查询: 用户可使用以下命令在指定路径下查看历史日志汇总$ bin/hadoop job -history output-dir 这条命令会显示作业的细节信息,失败和终止的任务细节. 关于作业的 ...