python查询mysql数据(3)
"""数据查询"""
import pymysql
import datetime
from pymysql import cursors
# import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='10.10.146.28',
port=3306,
user='admin_m',
passwd='fcfmTbRw1tz2x5L5GvjJ',
db='test',
charset='utf8mb4'
)
def query_data():
cursors = connect.cursor()
sql = "select * from employee"
cursors.execute(sql)
try:
results = cursors.fetchall()
for row in results:
fname=row[0]
lname=row[1]
age=row[2]
sex=row[3]
income=row[4]
# 输出结果
print("first_name=%s,last_name=%s,age=%s,sex=%s,income=%s"%(fname,lname,age,sex,income))
except Exception as e:
print("Error: unable to fetch data. Error info %s" % e)
finally:
cursors.close()
def main():
query_data()
if __name__ == "__main__":
main()