如何用Python操作数据库?( 二 )


import Pymysqltry: conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cur=conn.cursor() cur.execute('select * from students where id=7') result=cur.fetchone() print result cur.close() conn.close()except Exception as e: print(e) 

  • 创建testSelectMany.py文件,查询全部学生信息
 
#encoding=utf8import Pymysqltry: conn=Pymysql.connect(host='localhost',port=3306,db='test1',user='root',passwd='mysql',charset='utf8') cur=conn.cursor() cur.execute('select * from students') result=cur.fetchall() print result cur.close() conn.close()except Exception as e: print(e)实例一:参数
# 导入python操作mysql的模块import pymysqlimport time# 获取连接对象conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8')# 获取执行工具cur = conn.cursor()# sql语句,增删改,sql注入sql = 'insert into t_user(name,pwd,birthday) values(%s,%s,%s)'# 参数列表name = input('输入姓名:')pwd = input('输入密码:')birthday = input('输入生日:') # 2017年10月01日-->日期struct_time(--->2017-10-01)birthday = time.strptime(birthday,'%Y年%m月%d日') #这里我们就用到了时间与字符串的相互转换(详情见MySQL高级)params = [name,pwd,birthday]# 执行,返回值 。如果是增删改,返回受影响的行数,如果是查询,返回查询的行数count = cur.execute(sql,params)#提交conn.commit()print('受影响的行数:%s'%count)# 关闭cur.close()conn.close()实例二:抛出异常
# 导入python操作mysql的模块import pymysqltry: conn = None cur = None # 获取连接对象 conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8') # 模拟异常 # a = 1 / 0 # 获取执行工具 cur = conn.cursor() # sql语句,增删改 sql = 'insert into t_user(name,pwd,birthday) values("小伊","123456",str_to_date("2017年10月20日","%Y年%m月%d日"))' # 执行,返回值 。如果是增删改,返回受影响的行数,如果是查询,返回查询的行数 count = cur.execute(sql) # 提交 conn.commit() print('受影响的行数:%s' % count)except Exception as ex: # 打印异常信息,测试时候使用,项目上线,去掉 print(str(ex)) # 将异常继续抛出 # raisefinally: if cur != None: cur.close() if conn != None: conn.close()实例三:
# 导入python操作mysql的模块import pymysql# 获取连接对象conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='python01', port=3306, charset='utf8')# 获取执行工具cur = conn.cursor()# sql语句,增删改#sql = 'select birthday from t_user'sql = 'select id,name,pwd,birthday from t_user'# 执行,返回值 。如果是增删改,返回受影响的行数,如果是查询,返回查询的行数count = cur.execute(sql)print('查询的结果有%s条数据'%count)# 获取第一行# dateOne = cur.fetchone()# print(dateOne)# for temp in cur:# print(temp)s = 'id:%s,name:%s,pwd:%s,birthday:%s'for temp in dataAll: print(s%(temp[0],temp[1],temp[2],temp[3]))# 关闭cur.close()conn.close()封装
我们可以封装一个py文件,方便每次进行调用 。把这个库定义为:mySqlHelper
"""python操作mysql进行增删改查的封装1、增删改,代码类似2、查询代码分析1、获取连接对象2、sql语句不同,参数不同3、获取执行对象"""import pymysqlclass MysqlHelper: '''python操作mysql的增删改查的封装''' def __init__(self, host, user, password, database, port=3306, charset='utf8'): ''' 初始化参数 :param host: 主机 :param user: 用户名 :param password: 密码 :param database: 数据库 :param port: 端口号,默认是3306 :param charset: 编码,默认是utf8 ''' self.host = host self.port = port self.database = database self.user = user self.password = password self.charset = charset def connect(self): ''' 获取连接对象和执行对象 :return: ''' self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database, port=self.port, charset=self.charset) self.cur = self.conn.cursor() def fetchone(self, sql, params=None): ''' 根据sql和参数获取一行数据 :param sql: sql语句 :param params: sql语句对象的参数元组,默认值为None :return: 查询的一行数据 ''' dataOne = None try: count = self.cur.execute(sql, params) if count != 0: dataOne = self.cur.fetchone() except Exception as ex: print(ex) finally: self.close() return dataOne def fetchall(self, sql, params=None): ''' 根据sql和参数获取一行数据 :param sql: sql语句 :param params: sql语句对象的参数列表,默认值为None :return: 查询的一行数据 ''' dataall = None try: count = self.cur.execute(sql, params) if count != 0: dataall = self.cur.fetchall() except Exception as ex: print(ex) finally: self.close() return dataall def __item(self, sql, params=None): ''' 执行增删改 :param sql: sql语句 :param params: sql语句对象的参数列表,默认值为None :return: 受影响的行数 ''' count = 0 try: count = self.cur.execute(sql, params) self.conn.commit() except Exception as ex: print(ex) finally: self.close() return count def update(self, sql, params=None): ''' 执行修改 :param sql: sql语句 :param params: sql语句对象的参数列表,默认值为None :return: 受影响的行数 ''' return self.__item(sql, params) def insert(self, sql, params=None): ''' 执行新增 :param sql: sql语句 :param params: sql语句对象的参数列表,默认值为None :return: 受影响的行数 ''' return self.__item(sql, params) def delete(self, sql, params=None): ''' 执行删除 :param sql: sql语句 :param params: sql语句对象的参数列表,默认值为None :return: 受影响的行数 ''' return self.__item(sql, params) def close(self): ''' 关闭执行工具和连接对象 ''' if self.cur != None: self.cur.close() if self.conn != None: self.conn.close()


推荐阅读