Python操作MySQL操作规范——学习笔记
imooc学习地址:http://www.imooc.com/learn/475
课程内容:
1. Python访问DB的官方接口
2. Python开发DB程序的开发环境
3. Python访问DB的connection、cursor两大对象
4. Python执行增、删、改、查操作的实例讲解
5. 完整实例:银行转账实现
第一节:Python DB API
Python访问数据库的统一接口规范:https:www.python.org/dev/peps/pep-0249/
访问流程:
开始——创建connection——获取cursor——执行查询、执行命令、获取数据、处理数据——关闭cursor——关闭connection——结束
第二节:Python MySQL开发环境
Python代码(包含SQL语句)——Python2.7客户端(Python-MySQL connector)——MySQL服务器5.6(MySQL客户端工具SQLyog)
下载Python-MySQL-Connector:
- Windows32位MySQL_python-1.2.5下载地址:
https://sourceforge.net/projects/mysql-python/
安装遇到里问题,不能识别python2.7
提示python version 2.7 required,which was not found in the registry
解决办法:https://www.cnblogs.com/thinksasa/p/3283695.html- Windows64位MySQL_python-1.2.5下载地址:
- https://www.jb51.net/database/552384.html
一直装不好MySQLdb模块,快崩溃之时,发现一位难兄弟在博客https://blog.csdn.net/chinewwen/article/details/70259301中提到了一个血的教训,叫做不大写MySQLdb。(import MySQLdb)终于,我输入正确的写法之后终于给了我想要的结果。哎,大小写害死人呀。
一开始的问题源于安装的MySQL_python-1.2.5是32位操作系统的,在多次寻找合适的64位的资源后,终于在https://www.jb51.net/database/552384.html,找到想要的版本。安装成功。结果在命令栏输入不规范,结果一直出现“ImportError: No module named mysqldb”。而在书写正确后,就没有报错。结果如下图:
下载好SQLyog后发现不能登陆,想了下,之前安装MySQL设置的root的密码给忘了。后来重新装了MySQL,重新设置密码后,还是不能登陆,这个我就纳闷了。看了下报错SQLyog 报错2058,在这个博客下找到解决的办法https://blog.csdn.net/jared456/article/details/80380853,还需要一步在
登陆MySQL之后 ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;,其中password是密码。果然,可以登录SQLyog了。
学习——如何使用SQLyog将大量数据导入mysql数据库:https://mp.csdn.net/mdeditor/82023805
新想法,把爬虫抓取得数据变为list后存入数据库,可能要继续之前的python-mysql操作学习
第三节:Python访问DB的connection、cursor两大对象
链接对象:建立Python客户端和数据库的网络连接
创建方法:MySQLdb.Connect
(参数)
- host-字符串-MySQL服务器地址
- port-数字-MySQL服务器端口号
- user-字符串-用户名
- passwd-字符串-密码
- db-字符串-数据库名称
- charset-字符串-连接编码
(charset=utf-8,可以防止中文乱码)
connecction对象支持的方法
- cursor()使用该连接创建并返回的 游标
- commit()提交当前事务
- rollback()滚回当前事务
- close()关闭连接
实例:
import MySQLdb
conn = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='123123',
db='imooc',
charset='utf8'
)
cursor=conn.cursor()
print conn
print cursor
cursor.close()
conn.close()
输出结果:
<_mysql.connection open to '127.0.0.1' at 37f1fe8>
<MySQLdb.cursors.Cursor object at 0x00000000038C6A58>
数据库游标对象cursor
游标对象:用于执行查询和获取结果
cursor对象支持的方法:
- execute(op[,args])执行一个数据库查询和命令
- fetchone()取得结果集的下一行
- fetchmany(size)获取结果集的下几行
- fectchall()获取结果中剩下的所有行
- rowcount最近一次执行execute返回数据的行数或影响行数
- close()关闭游标对象
没有数据遍历rownumber=0
fetchone()——rownumber=1
fetchmany(3)——rownumber=2、3、4
fetchall()——rownumber=5、6
第四节:实例演示
select查询数据
- 开始
- 创建connection获取cursor
- 使用cursor.execute()执行select语句
- 使用cursor.fetch*()获取并处理数据
- 关闭cursor
- 关闭connection
- 结束
testcursor
import MySQLdb
conn = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='123123',
db='imooc',
charset='utf8'
)
cursor=conn.cursor()
print conn
print cursor
sql="select *from user"
cursor.execute(sql)
print cursor.rowcount
rs=cursor.fetchone()
print rs
rs=cursor.fetchmany(3)
print rs
rs=cursor.fetchall()
print rs
cursor.close()
conn.close()
testconnect
import MySQLdb
conn = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='123123',
db='imooc',
charset='utf8'
)
cursor=conn.cursor()
sql="select LoanId,sumCreditPoint from user"
cursor.execute(sql)
rs=cursor.fetchall()
for row in rs:
print "LoanId=%s,sumCreditPoint=%s" % row
cursor.close()
conn.close()
insert/update/delete更新数据库
- 开始
- 创建connection获取cursor
- 使用cursor.execute()执行i/u/d语句
- 判断是否出现异常
- 是——使用conn.rollback()回滚事务\否——使用conn.commit()提交事务
- 关闭cursor
- 关闭connection
- 结束
事务
访问和更新数据库的一个程序执行单元 - 原子性:事务中包括的诸多操作,要么都做,要么都不做
- 一致性:事务必须使数据库从一致性状态变到另一个一致性状态
- 隔离性:一个事务的执行不能被其他事务干扰
持久性:事务一旦提交,他对数据库的改变就是永久性的
开发中怎样使用事务?
关闭自动commit:设置conn.autocommit(False)
- 正常结束事务:conn.commit()
- 异常结束事务:conn.rollback()
import MySQLdb
conn = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='123123',
db='imooc',
charset='utf8'
)
cursor=conn.cursor()
sql_insert="insert into user(LoanId,sumCreditPoint) values(2000007,180)"
sql_update="update user set sumCreditPoint=-50 where LoanId=2000000"
sql_delete="delete from user where LoanId=2000005"
try:
cursor.execute(sql_insert)
print '1=',cursor.rowcount
#额外增加的条件:如果执行的数据为0个,则报异常终止后续的程序
if cursor.rowcount==0:
print 3/0
cursor.execute(sql_update)
print '2=',cursor.rowcount
if cursor.rowcount==0:
print 3/0
cursor.execute(sql_delete)
print '3=',cursor.rowcount
if cursor.rowcount==0:
print 3/0
conn.commit()
except Exception as e:
print e
conn.rollback()
cursor.close()
conn.close()
先在testyog数据库中新建account表
# coding:utf8
import sys
import MySQLdb
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("账户%s不存在"%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 "has_enough_money:"+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("账户%减款失败"%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 "reduce_money:"+sql
if cursor.rowcount!=1:
raise Exception("账户%s加款失败"%acctid)
finally:
cursor.close()
def transfer(self,source_acctid,target_acctid,money):
try:
#ctrl+1
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 = MySQLdb.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='123123',
db='testyog',
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()