python-数据库查询结果作为参数保存
1、下载安装pymysql
在cmd窗口输入如下命令后即可安装成功
pip install pymysql
2、数据库查询操作
1 import pymysql 2 3 def do_sql(sql): 4 # 打开数据库链接,pymysql.connect(host=, user=, passwd=, db=) 5 db = pymysql.connect('localhost', 'root', 'runa#2013', 'test0716') 6 7 # 使用 cursor() 方法创建一个游标对象 cursor 8 cursor = db.cursor() 9 10 # 使用 execute() 方法执行 SQL 查询 11 cursor.execute(sql) 12 13 # 使用 fetchone() 方法获取单条数据. 14 # data1 = cursor.fetchone() 15 # print('单条打印:', data1) 16 17 # 使用 fetchall() 方法接收全部的返回结果行. 18 data2 = cursor.fetchall() 19 # 关闭游标 20 cursor.close() 21 # 关闭数据库连接 22 db.close() 23 return data2 24 25 26 if __name__ == '__main__': 27 sql = 'SELECT s.`realName` FROM `s_user` s' 28 data = do_sql(sql) 29 for i in data: 30 print(i)
执行结果为: