Python 操作 mysql -> MySQLdb

首先需要下载一个模块:

pip3 install MySQL-python

如果出错,参考这篇文章:Python 解决 MySQLdb(MySQL-python) 安装失败的问题 -> windows 系统

接下来是代码:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb

localhost = "xxxxxxxx" # 你的数据库地址
username = "xxxxxxxx" # 你的数据库用户名
password = "xxxxxxxx" # 你的数据库密码
database = "xxxxxxxx" # 你的数据库实例
db = MySQLdb.connect(localhost, username, password, database, charset="utf8") # 注意编码
cursor = db.cursor()
cursor.execute("select * from account") # 尝试查询的 sql 语句
data = cursor.fetchone()
print(data)
data = cursor.fetchone()
print(data)

data_all = cursor.fetchall() # 获取所有的数据
for d in data_all:
    print(d)
print(len(data_all))
db.close()

猜你喜欢

转载自blog.csdn.net/qq_33811662/article/details/80822000