#coding=utf-8
'''
python操作mysql数据库
robotframework框架中用到了MySQLdb中间件和DatabaseLibrary第三方库
author:多测师_王sir
'''
'''
创建数据库连接对象需要的参数
host
string, host to connect
user
string, user to connect as
passwd
string, password to use
db
string, database to use
port
integer, TCP/IP port to connect to
'''
import MySQLdb #MySQLdb模块==》做mysql数据库自动化测试
#
# #创建一个连接数据库的对象
# #mysql数据库的默认端口号为3306 范围:3306-3309
db = MySQLdb.connect("192.168.131.128","root","123456","dcs46",3306)
#创建一个数据库的游标对象
#游标对象有2个作用:
#1.执行sql语句
#2.接受返回值
cursor = db.cursor() #创建一个游标对象
select_sql = "select * from student;" #定义了一个SQL语句
cursor.execute(select_sql) #通过游标对象调用execute实例方法执行SQL语句、执行后的结果被保存到了cursor对象中
#fetchone返回表中第一行的数据
one = cursor.fetchone() #并且返回查询到的内容、fetchone这个实例方法只返回第1行的数据
print one #(1L, 99L) 这返回的数据L表示python当中的长整型
print type(one) #<type 'tuple'>
#fetchall返回表中所有的内容
all = cursor.fetchall()
print all
print type(all) #<type 'tuple'>
#封装成为一个工具类
import MySQLdb
class Db_Utils:
def __init__(self,host,user,passwd,db,port):
'''
连接数据库所需要的参数
'''
self.host = host
self.user = user
self.passwd = passwd
self.db = db
self.port = port
def get_connection(self):
'''
创建了一个连接mysql数据库的对象
:return:
'''
db = MySQLdb.connect(self.host,self.user,self.passwd,self.db,self.port)
return db
def select_one(self,sql):
'''
封装一个查询表中第一行数据的工具方法
:return:
'''
try:
db = self.get_connection() #拿到了一个连接数据库的对象
cursor= db.cursor() #创建一个游标对象
cursor.execute(sql)
db.commit() # 再次往数据库提交数据或者执行的请求
one = cursor.fetchone() #拿到表中的第一行数据
return one
except Exception:
db.rollback() #数据库的回滚、把数据库代码的操作返回到上一次操作的状态
def delete_one(self,del_sql,sel_sql):
'''
封装一个删除表中特定数据并且返回表中剩余数据的工具方法
:param del_sql:
:param sel_sql:
:return:
'''
try:
db = self.get_connection()
cursor = db.cursor()
cursor.execute(del_sql) #删除
cursor.execute(sel_sql) #查询删除后表中剩余的数据
db.commit()
all = cursor.fetchall()
return all
except Exception:
db.rollback()
if __name__ == '__main__':
m = Db_Utils("192.168.131.128","root","123456","dcs46",3306) #创建一个对象
u = m.select_one("select * from student;") #对象调用实例方法
print u
#练习题:
#1.封装一个查询所有数据的工具方法
#2.封装一个删除表中所有数据的工具方法、并返回剩下的数据