我们在测试过程中,可能需要到数据库中拉去一些数据,为从测试准备。比如最近在做接口性能测试的时候,就需要很多数据来支撑,所以就需要的数据库去查询数据,下面就是python3 查询 mysql 并且保存到文件中,然后为接口做测试做准备。
1 #coding=utf-8 2 3 import pymysql as MySQLdb #这里是python3 如果你是python2.x的话,import MySQLdb 4 5 host = xxxx 6 user = xxxx 7 passwd = xxxx 8 port = xxxx 9 db = xxxx 10 class SelectMySQL(object): 11 def select_data(self,sql): 12 result = [] 13 try: 14 conn = MySQLdb.connect(host=host, 15 port=port, 16 user=user, 17 passwd=passwd, 18 db=db, 19 charset='utf8', ) 20 cur = conn.cursor() 21 cur.execute(sql) 22 alldata = cur.fetchall() 23 # print(alldata) 24 for rec in alldata: 25 result.append(rec[0]) #注意,我这里只是把查询出来的第一列数据保存到结果中了,如果是多列的话,稍微修改下就ok了 26 except Exception as e: 27 print('Error msg: ' + e) 28 finally: 29 cur.close() 30 conn.close() 31 32 return result 33 34 def get_result(self, sql, filename): 35 print(sql) 36 results = self.select_data(sql) 37 print('The amount of datas: %d' % (len(results))) 38 with open(filename, 'w') as f: 39 for result in results: 40 f.write(str(result) + ' ') 41 print('Data write is over!') 42 return results 43 44 if __name__ == '__main__': 45 sql = "select name from user" 46 select = SelectMySQL() 47 result1 = select.get_result(sql,'namemsg.txt') 48 print(result1)
在你脚本的目录下就会有namemsg.txt文件,里面就是你想要的文件了