Python3连接 MySQL 服务器使用PyMySQL,Python2中使用mysqldb。PyMySQL 遵循 Python 数据库 API v2.0 规范,并包含了 pure-Python MySQL 客户端库。
数据库操作的主要方法如下:
connect对象有如下方法:
close():关闭此connect对象, 关闭后无法再进行操作,除非再次创建连接
commit():提交当前事务,如果是支持事务的数据库执行增删改后没有commit则数据库默认回滚,白操作了
rollback():取消当前事务
cursor():创建游标对象
cursor游标对象有如下常用属性和方法:
excute(sql[,args]):该方法用于执行sql,可以接受两个参数,第一个为sql语句,第二个可以是一个元祖,并在sql语句里使用%s或%d等方式接收,这样可以处理sql中的变量。该方法的返回值为被影响的语句,我们可以获取之并加以进一步处理。
excutemany(sql,args):执行多个数据库查询或命令。例如插入一个列表,该列表中都是一元祖,每一个元祖对应一行数据。list1 = [
('a','1'),
('b','2'),
]
reCount = cursor.executemany('insert into EMPLOYEE(first_name, last_name) values(%s,%s)',list1)
print reCount
db.commit()
close():关闭此游标对象
fetchone():获取单条数据,返回一个字典dict,里面都是键值对,即数据库字段名:字段值;
fetchall():得到结果集中剩下的所有行,返回元祖,元祖里包含很多元祖,每个元祖是一行数据,只有值没有键;
fetchmany([size= cursor.arraysize]):得到结果集的下几行
常用属性
connection:创建此游标对象的数据库连接
arraysize:使用fetchmany()方法一次取出多少条记录,默认为1
lastrowid:获取当前处理行的id号
rowcount:一个只读属性,返回执行execute()方法后影响的行数。
# -*- coding:utf-8 -*-
importMySQLdb
# 对于mysql数据库的具体底层操作,例如连接数据库等都封装到这个类中
classMySqlHelper(object):
def __init__(self):
self.ip='127.0.0.1'
self.user='root'
self.password='123456'
self.dbname='webmonitor'
# 获取多条数据的方法
def get_truple(self,sql,*params):
try:
conn= MySQLdb.connect(self.ip,self.user,self.password,self.dbname)
cur= conn.cursor()
cur.execute(sql,params)
data= cur.fetchall()
return data
except Exception, e:
print e
finally:
cur.close()
conn.close()
def get_one(self,sql,*params):
try:
conn= MySQLdb.connect(self.ip,self.user,self.password,self.dbname)
cur= conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute(sql,params)
data= cur.fetchone()
return data
except Exception, e:
print e
finally:
cur.close()
conn.close()
# 对于mysql数据库的具体上层操作,例如sql的生成,在小程序中这一层可以略过
classSqlManipulate(object):
def __init__(self):
self.__helper=MySqlHelper()
def check_Validate(self,*params):
sql= "select * from webmonitor_hostinfowhere id>%s"
result=self.__helper.get_truple(sql,*params)
return result
# 前端调用
sqlmanipulate = SqlManipulate()
params=(1,)
result =sqlmanipulate.check_Validate(*params)
printresult