Python 与 MySQL 交互可以通过以下步骤实现:
- 安装 MySQL Connector Python 模块
可以使用 pip 命令安装 MySQL Connector Python 模块:
Copy codepip install mysql-connector-python
- 连接 MySQL 数据库
使用 MySQL Connector Python 模块中的 connect()
方法连接 MySQL 数据库。需要提供数据库主机名、用户名、密码以及数据库名等连接信息。例如:
pythonCopy codeimport mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
print(mydb)
- 创建数据库表
可以使用 MySQL Connector Python 模块中的 cursor()
方法创建游标,然后使用 SQL 语句创建数据库表。例如:
pythonCopy codemycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
- 插入数据
使用 SQL 语句插入数据到数据库表中。例如:
pythonCopy codesql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
- 查询数据
使用 SQL 语句查询数据库表中的数据。例如:
pythonCopy codemycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
- 更新数据
使用 SQL 语句更新数据库表中的数据。例如:
pythonCopy codesql = "UPDATE customers SET address = 'Canyon 123' WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
- 删除数据
使用 SQL 语句删除数据库表中的数据。例如:
pythonCopy codesql = "DELETE FROM customers WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
完整的 Python 与 MySQL 交互的示例代码如下:
pythonCopy codeimport mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
sql = "UPDATE customers SET address = 'Canyon 123' WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
sql = "DELETE FROM customers WHERE name = 'John'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
注意:实际应用中需要根据实际情况修改连接信息、SQL 语句以及数据。