如何在Python中使用mysql-connector库连接MySQL数据库?

  • Post category:Python

以下是如何在Python中使用mysql-connector库连接MySQL数据库的完整使用攻略,包括安装mysql-connector库、连接MySQL数据库、执行SQL语句等步骤。同时,提供了两个示例以便更好理解如何使用mysql-connector库连接MySQL数据库。

步骤1:安装mysql-connector库

在Python中,我们可以使用pip命令安装mysql-connector库。以下是安装mysql-connector库的基本语法:

pip install mysql-connector-python

在上面的语法中,我们使用pip命令安装mysql-connector库。

步骤2:连接MySQL数据库

在Python中,我们可以使用mysql-connector库连接到MySQL数据库。以下是连接MySQL数据库的基本语法:

import mysql.connector

# 打开数据库连接
db = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='test'
)

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 执行SQL语句
cursor.execute('SELECT VERSION()')

# 获取单条数据
data = cursor.fetchone()

# 打印查询结果
print('Database version:', data)

# 关闭游标和数据库连接
cursor.close()
db.close()

在上面的语法中,我们首先使用mysql.connector模块连接到MySQL数据库。然后,我们使用cursor方法获取操作游标。接着,我们使用execute方法执行SQL语句。最后,我们使用fetchone方法获取单条数据,并使用print函数打印结果。最后,我们使用close方法关闭游标和数据库连接。

步骤3:执行SQL语句

在Python中,我们可以使用execute方法执行SQL语句。以下是执行SQL语句的基本语法:

cursor.execute('SELECT * FROM table_name')

在上面的语法中,我们使用execute方法执行SQL语句。其中,SELECT * FROM table_name是要执行的SQL语句。

示例1

在这个示例中,我们使用mysql-connector库连接到MySQL数据库,并查询students中的所有数据。

import mysql.connector

# 打开数据库连接
db = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='test'
)

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 执行SQL语句
cursor.execute('SELECT * FROM students')

# 获取所有数据
data = cursor.fetchall()

# 打印查询结果
for row in data:
    print(row)

# 关闭游标和数据库连接
cursor.close()
db.close()

在上面的代码中,我们首先使用mysql.connector模块连接到MySQL数据库。然后,我们使用cursor方法获取操作游标。接着,我们使用execute方法SQL语句,查询students表中的所有数据。接着,我们使用fetchall方法获取所有数据,并使用for循环遍历查询结果,并使用print函数打印查询结果。最后,我们使用close方法关闭游标和数据库连接。

示例2

在这个示例中,我们使用mysql-connector库连接到MySQL数据库,并向students表中插入一条数据。

import mysql.connector

# 打开数据库连接
db = mysql.connector.connect(
    host='localhost',
    user='root',
    password='password',
    database='test'
)

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 执行SQL语句
sql = "INSERT INTO students(name, age, gender) VALUES ('Tom', 18, 'male')"
cursor.execute(sql)

# 提交到数据库执行
db.commit()

# 打印插入数据的主键ID
print('Insert ID:', cursor.lastrowid)

# 关闭游标和数据库连接
cursor.close()
db.close()

在上面的代码中,我们首先使用mysql.connector模块连接到MySQL数据库。然后,我们使用cursor方法获取操作游标。接着,我们使用execute方法执行SQL语句,向students表中插入一条数据。接着,我们使用commit方法提交事务。最后,我们使用lastrowid属性获取插入数据的主键ID,并使用print函数打印插入数据的键ID。最后,我们使用close方法关闭游标和数据库连接。

以上是如何在Python中使用mysql-connector库连接MySQL数据库的完整使用攻略,包括安装mysql-connector库、连接MySQL数据库、执行SQL语句等步骤。同时,提供了两个示例以便更好理解如何使用mysql-connector库连接MySQL数据库。