python3 链接mysql

安装pymysql

pip3 install PyMySQL -i  http://mirrors.aliyun.com/pypi/simple/

代码

import traceback

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="xxx",
                     database="test", charset="utf8")

cursor = db.cursor()

sql = "SELECT name,age FROM user"
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        name= row[0]
        age= row[1]
        print("{}-{}".format(name, age))
except:
    traceback.print_exc()

db.close()




标签: pymysql、cursor、traceback、age、row、面试
  • 回复
隐藏