python连接mysql读取数据

1. python连接mysql读取数据

以下是Python连接MySQL并读取数据的基本示例:

1.安装MySQL Connector模块

使用以下命令在Python中安装MySQL Connector模块:

pip install mysql-connector-python

2.导入模块

导入Python的MySQL Connector模块:

import mysql.connector

3.连接到MySQL服务器

首先,创建一个MySQL Connection对象并传递连接详细信息:

mydb = mysql.connector.connect(
  host="localhost",
  user="username",
  password="password",
  database="database_name"
)

在这里,我们将连接详细信息传递给MySQL Connector模块的connect()函数,并将结果存储在mydb变量中。请注意,这些详细信息包括MySQL服务器的主机名/ IP地址,用户名/密码以及要使用的数据库名称。

4.获取游标对象

接下来,使用mydb连接对象的cursor()方法来获取游标对象:

mycursor = mydb.cursor()

5.执行查询

使用游标的execute()方法执行查询语句或任何其他SQL查询:

mycursor.execute("SELECT * FROM customers")

上面的代码将从名为”customers”的表中检索所有行。

6.处理查询结果

使用游标的fetchall()方法检索查询的结果:

myresult = mycursor.fetchall()

上面的代码将获取所有结果并将其存储在myresult变量中。您可以使用该变量来处理结果。

7.关闭连接

最后,使用mydb连接对象的close()方法关闭连接:

mydb.close()

下面是完整的Python程序:

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="username",
  password="password",
  database="database_name"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

mydb.close()

上面的代码将从名为”customers”的表中检索所有行并将它们打印到控制台。您可以根据需要修改代码来处理查询结果。

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注