python3 pymysql操作数据库

#pymysql操作数据库
import pymysql
# 打开数据库连接
db = pymysql.connect(host="192.168.254.24", user="root",
                     password="root", db="mysql", port=3306)

# 使用cursor()方法获取操作游标
cur = db.cursor()

# 1.查询操作
# 编写sql 查询语句  user 对应我的表名
sql = "select host,user,password from user"
try:
    cur.execute(sql)  # 执行sql语句
    results = cur.fetchall()  # 获取查询的所有记录
    for i in results:#遍历结果
        print(i)
except Exception as e:
    raise e
finally:
    db.close()  # 关闭连接

猜你喜欢

转载自www.cnblogs.com/fengzi7314/p/10023949.html