python封装查询mysql_Python操作mysql数据库(封装基本的增删改查)

新学Python,在这里分享操作MySQL的全过程

1、安装MySQL-python-1.2.3.win-amd64-py2.7.exe,这是操作mysql数据库的python库,有32位和64位之分,看自机器下载

2、64位机器安装MySQL-python-1.2.3.win-amd64-py2.7.exe出现 which was not found the regidtry,请点这里

3、引入mysql库:

importMySQLdb

4、获取数据库连接:

conn=MySQLdb.connect(host='localhost',user='mjy',passwd='123',db='python',port=3306,charset='utf8')

connect连接对象的方法:

close()

--关闭的方法

commit()

--如果支持事务则提交挂起的事务

rollback()

--回滚挂起的事务

cursor()

--返回连接的游标对象

5、获取游标:

#该游标对象执行查询操作返回的结果是序列

cur=con.cursor()

#该游标对象执行查询操作返回的结果是字典(字典可以方便我们队查询的结果进行操作,所以我采用这种方法)

cur=con.cursor(MySQLdb.cursors.DictCursor)

游标对象的方法:

callproc(name,[params]) --用来执行存储过程,接收的参数为存储过程的名字和参数列表,返回受影响的行数

close()

--关闭游标

execute(sql,[params])--执行sql语句,可以使用参数,(使用参数时,sql语句中用%s进行站位注值),返回受影响的行数

executemany(sql,params)--执行单挑sql语句,但是重复执行参数列表里的参数,返回受影响的行数

fetchone()

--返回结果的下一行

fetchall()

--返回结果的 所有行

fetchmany(size)--返回size条记录,如果size大于返回结果行的数量,则会返回cursor.arraysize条记录

nextset()

--条至下一行

setinputsizes(size)--定义cursor

游标对象的属性:

description--结果列的描述,只读

rowcount

--结果中的行数,只读

arraysize

--fetchmany返回的行数,默认为1

6、我自己封装的一些基本操作

# -*- coding: cp936 -*-

importMySQLdb

classMysqldbHelper:

#获取数据库连接

defgetCon(self):

try:

conn=MySQLdb.connect(host='localhost',user='mjy',passwd='123',db='python',port=3306,charset='utf8')

returnconn

exceptMySQLdb.Error,e:

print"Mysqldb Error:%s"% e

#查询方法,使用con.cursor(MySQLdb.cursors.DictCursor),返回结果为字典

defselect(self,sql):

try:

con=self.getCon()

printcon

cur=con.cursor(MySQLdb.cursors.DictCursor)

count=cur.execute(sql)

fc=cur.fetchall()

returnfc

exceptMySQLdb.Error,e:

print"Mysqldb Error:%s"% e

finally:

cur.close()

con.close()

#带参数的更新方法,eg:sql='insert into pythontest values(%s,%s,%s,now()',params=(6,'C#','good book')

defupdateByParam(self,sql,params):

try:

con=self.getCon()

cur=con.cursor()

count=cur.execute(sql,params)

con.commit()

returncount

exceptMySQLdb.Error,e:

con.rollback()

print"Mysqldb Error:%s"% e

finally:

cur.close()

con.close()

#不带参数的更新方法

defupdate(self,sql):

try:

con=self.getCon()

cur=con.cursor()

count=cur.execute(sql)

con.commit()

returncount

exceptMySQLdb.Error,e:

con.rollback()

print"Mysqldb Error:%s"% e

finally:

cur.close()

con.close()

if__name__ =="__main__":

db=MysqldbHelper()

defget():

sql="select * from pythontest"

fc=db.select(sql)

forrowinfc:

printrow["ptime"]

defins():

sql="insert into pythontest values(5,'数据结构','this is a big book',now())"

count=db.update(sql)

printcount

definsparam():

sql="insert into pythontest values(%s,%s,%s,now())"

params=(6,'C#','good book')

count=db.updateByParam(sql,params)

printcount

defdelop():

sql="delete from pythontest where pid=4"

count=db.update(sql)

print"the:"+str(count)

defchange():

sql="update pythontest set pcontent='c# is a good book' where pid=6"

count=db.update(sql)

printcount

#get()

#ins()

#insparam()

#delop()

#change()

附查询结果:

你可能感兴趣的:(python封装查询mysql)