Python使用MySQL数据库的方法以及一个实例

使用环境:Windows+python3.4+MySQL5.5+Navicat

一、创建连接

1.准备工作,想要使用Python操作MySQL,首先需要安装MySQL-Python的包,在Python 3.x下,该包已经改名为MySQLClient。可以使用pip方式安装:

pip install MySQLClient

或者下载包文件,进行安装也可以。

2.Python使用MySQL的流程:

Python使用MySQL数据库的方法以及一个实例

3.启动MySQL服务器:以管理员身份启动“cmd”,输入命令:’net start mysql‘

Python中使用MySQL导入方法:import MySQLdb

4.创建Connection

  Connection:创建了Python客户端与数据库之间的网络通路。他的参数如下

参数名 类型 说明
host String MySQL的服务器地址
port int MySQL的端口号
user String 用户名
passwd String 密码
db String 使用的数据库
charset String 连接字符集

  Connection支持的方法:

方法名 说明
cursor() 创建并且返回游标
commit() 提交当前事物
rollback() 回滚当前事物r()
close() 关闭Connection

5.获取Cursor.

Cursor:游标对象,用于执行查询和获取结果,它支持的方法如下:

方法名 说明
execute() 用于执行一个数据库的查询命令
fetchone() 获取结果集中的下一行

fetchmany(size)

获取结果集中的下(size)行
fetchall() 获取结果集中剩下的所有行
rowcount 最近一次execute返回数据/影响的行数
close() 关闭游标

下面我们在Python中创建一个实例:

import MySQLdb

conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='',db='test',charset='utf8')

cursor=conn.cursor()

print(conn)
print(cursor) cursor.close()
conn.close()

运行程序结果如下:Python使用MySQL数据库的方法以及一个实例

从结果中我们可以看见成功创建了一个Connection和Cursor对象。

二、建立数据库,进行一些简单操作

1.简单的创建一个’user‘表,并且插入一些数据。user表中只有两个字段:userid和username。代码如下:

import MySQLdb
conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='',db='test',charset='utf8')
cur=conn.cursor() cur.execute("""
create table if not EXISTS user
(
userid int(11) PRIMARY KEY ,
username VARCHAR(20)
)
""")
for i in range(1,10):
cur.execute("insert into user(userid,username) values('%d','%s')" %(int(i),'name'+str(i)))
conn.commit() cur.close()
conn.close()

我们用Navicat打开数据库,查看一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pCYAjJRXHrV3TpwdpI329Z2tH5HMEGkKDqPVDEZlzyF5aiITAEb/uvb0ZLfu3NA8OxqVPYdgJDIBYPRVx+h3/YYLDxcrCqKt8qoNIoIREgBGJ7snz9w3XXq6PFdJEG2VV20QEYyQADA6fW/uIsrhd5IKRhIVAEaqzIoiXosrvqeNlOWTogAwuj7q7Bj33tGF2CKhZc95zTDirOBYenl1nG5gFwBGtyf8KFaE/YW/7DmvFUacdWELVoKtI0Z8bmAXAEaFQbSiKvaQ02c566an64kRrxvYBYBR32y8P7MSbWZBY1FjlLO8Oef21bhmCK8b2AWAEWKIuy62qIo9cNZF59YFQcrFqJY1Q3jdwC6Q0Wij35izSr+oMEpzhoaW9nZFqUmt9jVDSruBXQAY9aDMEM6kJsKaIRlpFCXL8tWlZkgJN7ALAKPOqXC3PsJdXl1sxR4YFfZvGYyga4aUcgO7ADDqGOcury4+jPhe15Sb1ABrhjTwWyMQjK6NrKnHvXd0ITaHn9QMkZoAMLr8BK0o4qfdG3sPf0KKPUhQABhdeLBwZXj1ZmaVfoKRFAWA0dmCAuqkZojUBIDRD3eNFx+iQJE4ChQhxR6kJgiMNLMXHlh/fI5qhhCMpCio0ciKRiM0qZHMEAmqWozO3DOpHtmujzotzkzydZXfSCRBUecH6StPV26+8AiPfiQiyhMKonV0jPvY90a4XSJ6/fT/bQ1Xn1yZ2xsAAAAASUVORK5CYII=" alt="" />,可以看到成功创建表,并且插入了十个数据。

2.我们操作一下Cursor里面的一些方法。

  execute()方法:执行SQL,将一个结果从数据库获取到客户端

  fetch*()方法:移动rownumber,返回数据。

例如我们有如下代码:

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)

结果如下:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAsUAAAB3CAIAAABkNKoYAAAMWklEQVR4nO3dW5KjOhKA4bOdlrcwERMTUWyjtAytovV4NtBsos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vb9vBp/vnyasYfbjGcnySo2a8yez7T4s34/jfVd14XQukahalmuscT3MyH+t+7veOxfCa2WTy02c4qX1Ad/vz7pQ9PCzp9t9vf73rkySIy//3j5Bh5fcapU8QcfqJ7P5Pgz5XMznr+yfCbHn/v7qdsyPyn2/bwaf6HvZ8Hrhyzfz/PXD2WOn7XlMzn+vXzK83zP/aKPsu0TL5fH6sEX49ouxV/mftFi+4NWPpPjz3f/2PyIU10+k+PPl8/H5iyiqMz+nhB/of29VL2ba38/HX/W7+dk3qegouT56FL8736/6EEoe8vn52NjrMrzSg//TrPj7FgbHvwhF/1VJvI40vP1xM5DDhK3d55PYxrn7PPnsf2wlnzuxf8iqmz57Ldlakuc7i6rJZ978b+IKmc+t1st/PyDT860v189bWfN57pejI2bSVYgn9H4X0SVdX+fIm9cG4aXKspnNP4XUV2/+D9P93nbr9u4xiWLoa0PjeeV9n+kZV/U7NfxJoKu64J3rg1///z+9/kGOxuL+zwcj51V27u21vEfRRUfLp64ves2w3G7VkHWks+9+I+iypnPeZzzYr+WfO7FfxRV5nxGz8cV5fNSPVEgn3bqdJ+tqKJ8RuM/iqpUPr2t7/i5F/9RVNGREzvLr9KdDyw9VpXi6N0ctJRKtpd8Rl4in9eRT13kUxf51HX+mj/Z/fOVv8Pzs0vKvb3ks67PfzfkUxf51EU+39n99QQAAKgd9QQAAJCingAAAFLUEwAAQIp6AgAASFFPAAAAKeoJAAAgRT0BAACkqCcAAIAU9QQAAJCingAAAFLUEwAAQIp6AgAASFFPAAAAKeoJAAAgRT0BAACkqCcAAIAU9QQAAJCingAAAFL/BwDtiN4YwRSoAAAAAElFTkSuQmCC" alt="" />

我们可以看出执行查询全部数据后,rowcount为10

执行fetchone()方法后返回一个数据,执行fetchmany(3)后返回3条数据,执行fetchall()后返回剩下的所有数据。

再有如下代码:

res=cursor.fetchall()
for row in res:
print('userid=%s,userna=%s' %row)

此时的执行结果为:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAM8AAACsC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s13dbVzLl251u/p+kl7vT6mruEtLL6fTylW5siHve9gSkl4XTiNvwXywVNOI2oAK4DfABtwE+4DbAB9wG+IDbAB9wG+ADbgN8wG2AD7gN8AG3AT4kug3p5VaRlSfNSS+fY0v4Z3wOEnST5baOvscVZCJBN3EzKdxWCAm6CXVbflpEFxXTyxJ005deXlTbd5bfRmCQXvZCFXm6FUJfenkR2kvNpGNqpeuipo5v6spuZ0vHHL84pWDW/lN1K4G+9HLYIN69HEn44d3LFz+KnhfvXk6380V6mapbCfSll8N+4t3LkbEN717ez3L6g1lCetmYfhjs/jXevXz64vLdyzHdOFGZXt4OxruXae9evtCNDXHP256A9LJwGnEb0ssqaMRtQAVwG+ADbgN8wG2AD7gN8AG3AT7gNsAH3Ab4gNsAH3Ab4ANuA3xIdBvSy60iK08a7M1PNbUGQ/g316umrm6y3Nbl7WC+2tcK0lTXTdxMmiNEP3z49502QHXdhLotmRa5zA3IJ9gDHN3GXOzU9XVTm15eu5S+WMNC3q5LX3o5T7dCqE0vryLOzSUqLF0XNXV8U1d2O8fQ8qFLqfRytm4l0JdejvQT6eUw4Xfx7mWKbiXQl14289X6OKf5Vl2J9o2k9DJVtxLoSy93x1kA6eXY2BbvP0m3EuhLL3fHtd12Vx+sS9jqoqaOL4sitpOw3WX/Y7pxojK97J/XX3ghvZxOL1/pxoa4521PQHpZOI24DellFTTiNqCC/wFxUGBzFsG0mQAAAABJRU5ErkJggg==" alt="" />

3.上面介绍的便是数据库中常说的Select操作,下面我们介绍数据的更新,即:insert、update、delete操作。值得注意的是在这部分操作时需要注意的是是否数据发生异常,如果数据没有发生异常,我们便可以直接使用commit()进行提交(注:如没有使用commit,则数据库不会发生任何变化)。但是如果出现了异常,那么久需要使用rollback()进行回滚。

3.1先来看一个没有异常,正常提交的例子:

sql_insert='insert into user(userid,username) values(10,"name10")'
sql_update='update user set username="name91" where userid=9'
sql_delete='delete from user where userid=3' cursor.execute(sql_insert)
print(cursor.rowcount)
cursor.execute(sql_update)
print(cursor.rowcount)
cursor.execute(sql_delete)
print(cursor.rowcount)
conn.commit()

上面的操作即是:添加一条(10,’name10‘)的数据、将userid=9的username修改为’name91‘,删除userid=3的数据,执行上面代码后我们来用Navicat查看一下数据:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAAD/CAIAAAA7RQ7cAAAgAElEQVR4nO2d+XcTV5r367+Y6e4QMMbYmJ1gH5o/YN7zNt3T00tCAiTqNsExZKZnprsn6fR7zuQ9k466gTRxSCfsIHYQm21sEeMFGxtvWN5kW7ZUlrxK1r6W9pLmh1tVKsla6SuVXHW/5/mhKFVJj+79cO916XnugxVv2uH2kX0zzj7c0Ys7enHHks331uHf2pGQ/g5h6zdtd/tCvbi9V23rUdteqGxLVu+bVf/BtWNIq1vY+rLtbl+oZ9ryYsr8QmnuUpoWzcQvfvVvXDuGtLqFrS/b5vIGu5Wm55OGzonlZ+PL8ybXz947xrVjSKtbWFHpNpc3+HxiuVOheza21D66OG9w/vRgTSQSaUFCelVhRaVbXd5Ah0L3bGyxfWShdXhudtnxkwPVESSkv0PYuo1bXJ5Ax+hi+8h869Dc00Ht7LL9x2+/L0FC+jtEgdU+stA2PNci1z6Va2eXbQCstFTiOL7gjfDAcBzPw3/iwhfEdsDWbdzi9ASejc4zI5aWHrEy8YNzJhBYEAUZLJcn8Gx0oW1koXVorkU+O7ds/8k7RxBYAhR8sNrHFttGF9tGFtqG5+cMjn8++AECS4CCDZY30DGu71DogM2bXP/y7jEElgAFHaxgl9LYrTR2K41dStOihfjFr/6NM7DGv9yF/fDT8RXn66qxyi+7EFi5FEywikq3un2hXpW1V20DprN63zz8nwgsAQoqWGXb3L5Q/4xzYMY5oHENaNx6u//t6t8X3FSIwMq9YIK1ftN2wk/K5zyDcx75vEc+7zU4ggdqPpJIJF5fIIWFQiSO422WSJ7sbjW2+8truXlzHMdTf1khGOhQaGAVl+8g/OHhRf/won9kyT+8FDC6QgeP/iE7sAa/LMeq/7zi+NqffohRol+1yPbRp8r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vuVTUMGKjlj+JmVMZQo+gZXdiJXDWjpZ+5ZPQZ4KbR6yXkE0gNmQNRWu8lo6KzovFpIsSp5ArKWTvW/5FNS/CqPJFK56BcEuILDKS54kn31WdHkasCDW0snet3wKJlhFpdss7sCdfuO9QXYBgVUNFrtcDWu5HT2dul5hTmvpZO1bPgX3AekWs9N/vWvhVu+ydNDycMTJ7N2AaukITVB/0inZbHJ4L7XNXHsOdpux4Sb/gaMfo5InAhRMsNYUbzLaPee+U15u11zvXrpLVaZAYAlRUMEC6V+Pxy48VV3tnNJq6hcAAADrSURBVL/dF914DdXSEZrghs2ULlvdp+uGzz5RXnkGwmZ8IGwGlTwRmqCCVVS6bHV/9VB+VjZ5uV17swfU0kFgCVE5AOvR0NknyivPtGDEAlMhytIRoOCBRUWQjpxvnpZ0zN3uM6gNVIo9rM9AEqCwNcWbjDbiTNP4pVb8etfi3QFz5hGkSEjJBLbj9l5onpZ0zN7s0d8btDLPsbj2DWkVC1tbstns9EmeaW90L90dMIHSvRmGJiMhJRO2rnSrxeW/+UJ3t990f8jG3niNa9+QVrGw9WXb6Zh3e92oq2Hcq7FQP0Jz7RvSKtb/Am21v0AFhd5VAAAAAElFTkSuQmCC" alt="" />从结果可以看到代码执行正常。

3.2.再来看一个有异常的数据

sql_insert='insert into user(userid,username) values(10,"name10")'
sql_update='update user set username="name91" where userid=9'
# sql_delete='delete from user where userid=3'
# ##error
sql_delete='delete from user where useri=3'
try:
cursor.execute(sql_insert)
print(cursor.rowcount)
cursor.execute(sql_update)
print(cursor.rowcount)
cursor.execute(sql_delete)
print(cursor.rowcount)
except Exception as e:
print(e)
conn.rollback()

这里的insert和update操作一样,只不过把delete里面的userid字段错误的写成了useri,执行代码:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAakAAACACAIAAAA+mgFGAAAJ9ElEQVR4nO3d34GrKBvH8W3nmDZe2xjKoIqlgt07mljS3HuBICIg/kni5Pl+Ls7JOEYByU/EJPPXAwDk+evTBQCADyD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GQiOwDIBHZB0Aisg+ARGQfAInIPgASkX0AJCL7AEhE9gGQ6P87x2OdwLn7hgAAAABJRU5ErkJggg==" alt="" />

可以看到显示出异常,这时我们来看一下数据库数据:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAALoAAADuCAIAAAABc4pHAAAOc0lEQVR4nO2dT2/byBmH5/P42FqCoo8Qf4cQkNdC8il6yIYL24tE197SnLK6RA4QFVs7h0VPu1hdVs4eIt6KtiicCOpuLKuJLfYw/DP8NzP0kHxp8vdgDgxJSe/wfTRDOTNDtgJAG0YdALhLsFMAtGEuANqw5wBoo2hdHMf5x5XbgOI4TjXfv5pjeB2gS7uALtAlB9AFuuQAukCXHNxBXc6f/YHd+9N5Yv9kyLrP/g5dygS6QJcc3EFdsgp0KR9TXa42n7PK9fWN4zhvP7oVle+GbPfZi3Le3HEcSU1bUnhCK9Hl52c7bPhNYvvF1/eYh3/043TP37Xz9eLtR/ftx8WjXbb33XSPMbb77IX4VsLJjB8tW5d333bZV5PE9vlxzw/CP7p5PfB3dY9/vdp8vtr8etRlg5PXA8ZY99vzzesB6x0dfxU9h7+tx+AkeKve0Ym3f3Dy+eok8aqUj6ufLuur/2UVtS6RxAfpv/foZ1ewxNtgKbZN9xg/wX370f3GKlcXr17nx122P4ltizu9cjJgvcNzvv3usMsGE2+DhWeeDBhjgxP/rfj57w4Hx3N+wmTfP/lkwBjrHs+9neKrghOSH1dwqUKXsw/bsw/bs5+e7rADO779Zo8xxnqPftp6p708YFF2Hr8/+/D+0S7be7mNv9XLA7b79C8fhNeK/yy0KHTh6QwT5idVoHv0LpHIWI7Dl8+PgrYqaUPadvrH3Sldbm6UuvDy/tGuL016yuuvS/i1ZkH+un4jET1Bocv5cTdIdnrjkaFLyscVXHhCjXS5XG+yyvXNjeM4pxfb04vt6Y9Pd1jv4Y/b04vt88c9xg6eXGxPf3z68OX29GJ7evH+4S67/3J7evHmPuMb29OL7ZMHB08iR4O34vvFk98/3GVs9+nzC/+0QovjO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Ae6hPhf5pQvtXCZSp8JIAmDHFNdmjW0O8h5/J4hqkvZMwEywyAHugTExkRmdUZlzwSQhUFOibrcsZkA0fuE2F2DQpcCZwJIwyDHVJfmDO2OfJUjY/TdKmcCSMMgB7qEiKsfZP/dpfSZAJIwyDHVBTMBWoWpLhja3SqgixbQhWOqC2YCtApTXTC0u1VAFy2gC8dUF8wEaBtGusgPO46zbASr1Yo6hFoAXbSALhzoogV04UAXLaALB7poAV040EUL6MKBLgIz239mfMeeRY5Uqkt2GORAl4CxxZg19jejmapQF1kY5JjqohzaTV1BbSK5mdmdSKKq00UaBjnQxSeeJ/8rvlwuI7qMLdaxbSveW4Q9SPDCscU69tjbb415wxHrY/xdwU5pGOSY6qIc2k1dQW1mdkfsBZhEF//YzO54uZ3Zlp/jsDMZW4EF3IrwVcEJgRr+XmkY5EAXgeCr3rFtK6sziuVY0r6IZ6Zthy1LooHJCIOcEnXhMwGoK3g7xlb0W63QZWZ3gmSnNx4ZuihkiIdBjqkuyqHd1BW8Dck8KnQR9gmdiUoX8UfQcjm24mbU74cRdAmR/blD1RkJr7Us3dZlmXqDXOO/upjropwJQF3BYsBfdTmmuiiHdlNXsBigCwe6aAFdOKa6KGcCUFewGKALx1QX5dBu6goWA3ThQBctoAvHVBfMBGgbRrqYvBi0DegCcgBdQA6gC8gBdAE5gC4gB9AF5AC6gBxAF5AD6AJyAF1ADqALyAF0ATn4P1qUrP92RY28AAAAAElFTkSuQmCC" alt="" />数据没有任何改变。这就是rollback()的作用

因此,我们以后再写增删改查操作时,最好把操作放入一个try控制块中,来避免一些不必要的错误。

下面是一个银行转账的实例:

#-*-encoding:utf-8 -*-

import MySQLdb
conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='199331',db='test',charset='utf8')
cur=conn.cursor()
##创建数据表
cur.execute("""
create table if not EXISTS account(
accid int(10) PRIMARY KEY ,
money int(10)
)
""")
###插入两行数据
cur.execute('insert into account(accid,money) VALUES (1,110)')
cur.execute('insert into account(accid,money) VALUES (2,10)')
conn.commit() cur.close()
conn.close()
#-*- encoding:utf-8 -*-
import sys
import MySQLdb class TransferMoney(object):
def __init__(self,conn):
self.conn=conn
def check_acct_available(self,accid):
cursor=self.conn.cursor()
try:
sql='select * from account where accid=%s' %accid
cursor.execute(sql)
print('check_acct_available'+sql)
rs=cursor.fetchall()
if len(rs)!=1:
raise Exception('账号%s 不存在' %accid)
finally:
cursor.close()
def has_enough_money(self,accid,money):
cursor=self.conn.cursor()
try:
sql='select * from account where accid=%s and money>%s' %(accid,money)
cursor.execute(sql)
print('check_money_available'+sql)
rs=cursor.fetchall()
if len(rs)!=1:
raise Exception('账号%s 没有足够钱' %accid)
finally:
cursor.close()
def reduce_money(self,accid,money):
cursor=self.conn.cursor()
try:
sql='update account set money=money-%s where accid=%s' %(money,accid)
cursor.execute(sql)
print('reduce money'+sql)
rs=cursor.fetchall()
if cursor.rowcount!=1:
raise Exception('账号%s 减款失败' %accid)
finally:
cursor.close()
def add_money(self,accid,money):
cursor=self.conn.cursor()
try:
sql='update account set money=money+%s where accid=%s' %(money,accid)
cursor.execute(sql)
print('reduce money'+sql)
rs=cursor.fetchall()
if cursor.rowcount!=1:
raise Exception('账号%s 加款失败' %accid)
finally:
cursor.close()
def transfer(self,source_accid,target_accid,money):
###检测两个账号是否可用
try:
self.check_acct_available(source_accid)
self.check_acct_available(target_accid)
####检测付款人是否有足够的钱
self.has_enough_money(source_accid,money)
self.reduce_money(source_accid,money)
self.add_money(target_accid,money)
self.conn.commit()
except Exception as e:
self.conn.rollback()
raise e if __name__=='__main__':
source_accid=sys.argv[1]
target_accid=sys.argv[2]
money=sys.argv[3] conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='199331',db='test',charset='utf8')
tr_money=TransferMoney(conn) try:
tr_money.transfer(source_accid,target_accid,money)
except Exception as e:
print('出现问题'+str(e))
finally:
conn.close()
上一篇:Yii2.0登录详解(下)


下一篇:HIVE中的几种排序