一、数据库操作的基本流程
1、安装并导入操作mysql数据库的模块:pymysql
2、与数据库建立连接:conn = pymysql.connect(系列参数)
常用的系列参数包含:
host、user、password、port、database、charset(编码方式)、cursorclass(用于指定查询结果的数据格式,默认是tuple)
3、创建游标:用于操作sql语句
cur = conn.cursor()
4、执行sql语句
cur.execute(sql语句) # 返回值为查询结果的数量
5、获取查询的结果
5.1、获取单条查询结果
one = cur.fetchone()
5.2、查询所有的查询结果
all = cur.fetchall()
6、关闭连接资源
cur.close()
conn.close()
二、代码实现
1 import pymysql 2 3 # 1、建立连接 4 conn = pymysql.connect( 5 host="api.lemonban.com", 6 user="future", 7 password="123456", 8 port=3306, 9 database="futureloan",10 charset="utf8",11 cursorclass=pymysql.cursors.DictCursor # 将查询的结果使用字典进行保存(默认使用元组进行保存)12 )13 14 # 2、创建游标15 cur = conn.cursor()16 17 # 3、执行sql语句18 sql = "select * from member limit 3"19 cur.execute(sql) # 返回值为查询结果的数量20 # 4、获取单条查询的结果21 one = cur.fetchone()22 print("单条查询的结果为:",one)23 # 5、获取所有的查询结果24 all = cur.fetchall()25 for item in all:26 print(item)27 pass28 # 6、关闭连接资源29 cur.close()30 conn.close()
三、封装数据库操作流程
要求:在建立数据库连接时,参数通过配置文件获取
1 import pymysql 2 3 from integration1.Commons.handle_config import handleConfig 4 5 class HandleDB(): 6 7 def __init__(self): 8 # 建立连接 9 self.conn = pymysql.connect(10 host=handleConfig.get("mysql","host"),11 user=handleConfig.get("mysql","user"),12 password=handleConfig.get("mysql","password"),13 port=handleConfig.getint("mysql","port"),14 database=handleConfig.get("mysql","database"),15 charset="utf8",16 cursorclass=pymysql.cursors.DictCursor17 )18 # 创建游标19 self.cur = self.conn.cursor()20 pass21 # 获取1条数据22 def select_one_data(self,sql):23 self.cur.execute(sql)24 return self.cur.fetchone()25 # 获取所有数据26 def select_all_data(self,sql):27 self.cur.execute(sql)28 return self.cur.fetchall()29 #获取查询的条数30 def get_count(self,sql):31 return self.cur.execute(sql)32 33 def update_data(self,sql):34 self.cur.execute(sql) # 更新数据库35 self.conn.commit() # 提交36 pass37 38 # 关闭操作39 def close(self):40 self.cur.close() # 关闭游标41 self.conn.close() # 关闭连接42 pass43 44 if __name__ == '__main__':45 sql = "select * from member limit 3"46 handleDB = HandleDB()47 count = handleDB.get_count(sql)48 print(count)49 one = handleDB.select_one_data(sql)50 print(one)51 all = handleDB.select_all_data(sql)52 print(all)
今后,如果我们需要操作mysql的数据库资源时,只需要导入该模块即可。通过实例化HandleDB,就可以进行相应的查询操作。
四、应用
要求:随机生成一个手机号码,要求生成的手机号码未在数据库中注册
思路:
1、先生成符合要求的11位手机号码
2、通过手机号字段查询数据库,根据查询结果确定手机号码是否已在数据库中注册:
2.1、若已存在,重复执步骤1和2
2.2、若不存在,则返回生成的手机号码
1 import random 2 3 from integration1.Commons.handle_db import HandleDB # 导入操作数据库的类 4 5 prefix = [133, 149, 153, 173, 177, 180, 181, 189, 199, 6 130, 131, 132, 145, 155, 156, 166, 171, 175, 176, 185, 186, 166, 7 134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 172, 178, 182, 183, 184, 187, 188, 198 8 ] 9 10 def get_new_phone():11 handleDB = HandleDB()12 while True:13 # 生成电话号码14 phone = __generate_phone()15 #校验生成的号码是否已存在数据库中16 sql = "select * from member where mobile_phone = '{}'".format(phone)17 count = handleDB.get_count(sql)18 if count == 0: # 如果生成的手机号码在数据库中不存在,则返回该手机号码19 handleDB.close()20 return phone21 pass22 23 def __generate_phone():24 # 生成电话号码的前缀25 pre = prefix[random.randint(0,len(prefix)-1)]26 phone = str(pre)27 for _ in range(8):28 phone += str(random.randint(0,9))29 pass30 return phone31 pass32 33 if __name__ == '__main__':34 print(get_new_phone())