Python 可以通过 MySQL 官方提供的驱动程序 MySQL Connector/Python 来控制 MySQL 数据库。以下是一个使用 Python 控制 MySQL 的详细步骤:
安装 MySQL Connector/Python:在 Python 环境中使用 pip 安装 MySQL Connector/Python:
pip install mysql-connector-python
导入 MySQL Connector/Python:在 Python 脚本中导入 MySQL Connector/Python 模块:
import mysql.connector
连接 MySQL 数据库:使用 MySQL Connector/Python 提供的 `connect()` 方法来连接 MySQL 数据库:
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
其中,`host` 为数据库服务器地址,`user` 和 `password` 为数据库登录的用户名和密码,`database` 为要连接的数据库名称。
创建数据库表:使用 MySQL Connector/Python 提供的 `cursor()` 方法创建游标对象,使用游标对象执行 SQL 语句创建数据库表:
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
插入数据:使用游标对象执行 SQL 语句插入数据:
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
其中,`%s` 为占位符,用于接收要插入的数据。`val` 变量为要插入的数据,`execute()` 方法中的第二个参数为要插入的数据。
查询数据:使用游标对象执行 SQL 语句查询数据:
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
其中,`fetchall()` 方法返回所有查询结果。
更新数据:使用游标对象执行 SQL 语句更新数据:
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
其中,`WHERE` 子句用于指定要更新的数据行。
删除数据:使用游标对象执行 SQL 语句删除数据:
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
其中,`WHERE` 子句用于指定要删除的数据行。
关闭数据库连接:使用 `close()` 方法关闭数据库连接:
mydb.close()
实际使用时可以根据具体需求进行调整。