用python连接MySQL实验原理
Python可以通过使用第三方库mysql-connector-python来连接MySQL数据库。这个库可以通过pip命令安装。在连接MySQL数据库之前,需要先在MySQL中创建一个数据库,并在该数据库中创建一个或多个表。
下面是连接MySQL数据库的步骤:
- 导入mysql.connector库
import mysql.connector
- 建立连接
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
- 创建游标
mycursor = mydb.cursor()
- 执行SQL语句
mycursor.execute("SELECT * FROM customers")
- 获取结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整代码示例:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
注:在连接MySQL数据库之前需要先安装mysql-connector-python库,可以通过以下命令安装:
pip install mysql-connector-python
``
原文地址: http://www.cveoy.top/t/topic/fmCe 著作权归作者所有。请勿转载和采集!