如何在Python中使用MySQL数据库?用法示例教程

2021年11月17日03:22:08 发表评论 895 次浏览

Python如何使用MySQL?本文带你了解如何使用 MySQL 连接器在 Python 中连接到 MySQL 数据库、创建表、插入和获取数据,并结合一些具体的Python使用MySQL示例

MySQL是最流行的开源关系数据库管理系统 (RDBMS) 之一,它现在由 Oracle Corporation 开发、分发和支持。

在本教程中,你将使用MySQL 连接器 Python 库 来:

  • 连接到 MySQL 数据库
  • 创建数据库
  • 创建表
  • 将数据插入表
  • 从表中获取数据

相关: 如何在 Python 中使用 MongoDB 数据库。

如何在Python中使用MySQL?首先,你需要在你的机器上运行一个 MySQL 服务器实例,如果你使用的是 Windows,我建议你安装XAMPP。如果你使用的是 Linux 机器(Ubuntu 或类似机器),请查看本教程。如果你使用的是 macOS,请通过本教程运行以安装 MySQL。

其次,让我们安装 MySQL 连接器 Python 库以及 tabulate 模块:

pip3 install mysql-connector-python tabulate

我们将可选地使用tabulate模块以类似于常规 MySQL 客户端的方式输出获取的数据。

连接到 MySQL 数据库

Python使用MySQL示例:让我们导入 MySQL 连接器并将其连接到我们的数据库:

import mysql.connector as mysql
from tabulate import tabulate

# insert MySQL Database information here
HOST = "localhost"
DATABASE = ""
USER = "root"
PASSWORD = ""

# connect to the database
db_connection = mysql.connect(host=HOST, database=DATABASE, user=USER, password=PASSWORD)
# get server information
print(db_connection.get_server_info())

Python如何使用MySQL?我们使用mysql.connector.connect()方法连接到数据库,它接受 4 个参数:

  • host:我指定"localhost"为主机,这意味着我们正在连接到我们的本地 MySQL 服务器(安装在我们的机器上)。但是,如果要连接到远程 MySQL 服务器,则需要进行一些配置,请查看 本教程 ,其中我向你展示了如何设置 MySQL 服务器以接受远程连接。
  • database:这是你要连接的数据库的名称,将数据库设置为空字符串只会连接到 MySQL,而不是实际的数据库,因此我们将手动创建我们的数据库。
  • user: root是 MySQL 中的默认用户,你当然可以使用另一个。
  • password: 这是用户的密码,默认情况下root用户的密码是空字符串(当然,这只是为了开发)。

之后,我们调用了get_server_info()方法来打印服务器信息,这是目前为止的输出:

5.5.5-10.1.32-MariaDB

如果你获得了服务器信息,则一切正常。

让我们看看我们在哪个数据库中:

# get the db cursor
cursor = db_connection.cursor()
# get database information
cursor.execute("select database();")
database_name = cursor.fetchone()
print("[+] You are connected to the database:", database_name)

请注意,在我们执行任何 MySQL 命令之前,我们需要创建一个游标。一个游标是在执行SQL语句时,在MySQL服务器实例创建的临时工作区。

这是我的输出:

[+] You are connected to the database: (None,)

复制当然,我们没有连接到任何数据库,在我们这样做之前,让我们先创建一个。

创建数据库

如何在Python中使用MySQL?由于我们不在任何数据库中,我们需要创建一个:

# create a new database called library
cursor.execute("create database if not exists library")

它就像执行常规 MySQL 命令一样简单,我们正在使用,"if not exists"因此如果你再运行一次代码,你将不会收到任何“数据库存在”错误。现在让我们处理这个数据库:

# use that database 
cursor.execute("use library")
print("[+] Changed to `library` database")

创建表

Python使用MySQL示例:要创建表,我们需要做的就是将正确的 SQL 命令传递给该cursor.execute()方法:

# create a table
cursor.execute("""create table if not exists book (
    `id` integer primary key auto_increment not null,
    `name` varchar(255) not null,
    `author` varchar(255) not null,
    `price` float not null,
    `url` varchar(255)
    )""")
print("[+] Table `book` created")

复制我们刚刚创建了一个有 5 列的 book 表,只是为了演示,注意我使用了三双引号让我们可以轻松地跳到新行。

将数据插入表

Python如何使用MySQL?要将数据插入到表中,我们需要一个数据源,你可能希望将抓取的数据插入到数据库中,或者在本地文件中插入一些数据,无论源是什么,对于本教程,我们将从常规 Python 插入字典,只是为了方便:

# insert some books
books = [
    {
        "name": "Automate the Boring Stuff with Python: Practical Programming for Total Beginners",
        "author": "Al Sweigart",
        "price": 17.76,
        "url": "https://amzn.to/2YAncdY"
    },
    {
        "name": "Python Crash Course: A Hands-On, Project-Based Introduction to Programming",
        "author": "Eric Matthes",
        "price": 22.97,
        "url": "https://amzn.to/2yQfQZl"
    },
    {
        "name": "MySQL for Python",
        "author": "Albert Lukaszewski",
        "price": 49.99,
    }
]
# iterate over books list
for book in books:
    id = book.get("id")
    name = book.get("name")
    author = book.get("author")
    price = book.get("price")
    url = book.get("url")
    # insert each book as a row in MySQL
    cursor.execute("""insert into book (id, name, author, price, url) values (
        %s, %s, %s, %s, %s
    )
    """, params=(id, name, author, price, url))
    print(f"[+] Inserted the book: {name}")

所以我们在这里插入了几本书,注意我们用来"%s"替换params参数中传递的实际数据字段,这是由于包括SQL注入预防和性能在内的多种原因。

这是我的输出:

[+] Inserted the book: Automate the Boring Stuff with Python: Practical Programming for Total Beginners
[+] Inserted the book: Python Crash Course: A Hands-On, Project-Based Introduction to Programming
[+] Inserted the book: MySQL for Python

如果你现在去你的 MySQL 客户端,无论是PhpMyAdmin还是命令行,你都找不到这些新插入的书,那是因为我们需要提交:

# commit insertion
db_connection.commit()

如何在Python中使用MySQL?使用 commit 的主要原因是结束当前事务(在本例中,插入 3 本书)并使事务中的所有更改永久化。

与提交相反的是回滚,它基本上意味着取消当前事务所做的所有修改(在这种情况下,不是插入 3 本书),如果需要,你可以使用db_connection.rollback()。

有关事务的更多信息,请查看MySQL 的相关文档

从表中获取数据

Python使用MySQL示例:现在让我们从实际数据库中获取我们刚刚插入的数据:

# fetch the database
cursor.execute("select * from book")
# get all selected rows
rows = cursor.fetchall()
# print all rows in a tabular format
print(tabulate(rows, headers=cursor.column_names))

Python如何使用MySQL?我们执行 select 命令并使用cursor.fetchall()方法抓取所有行,如果你只想获取第一行,也可以使用fetchone()方法。

然后我们在tabulate模块的帮助下以表格格式打印所有返回的行,检查我的输出:

  id  name                                                                              author                price  url
----  --------------------------------------------------------------------------------  ------------------  -------  -----------------------
   1  Automate the Boring Stuff with Python: Practical Programming for Total Beginners  Al Sweigart           17.76  https://amzn.to/2YAncdY
   2  Python Crash Course: A Hands-On, Project-Based Introduction to Programming        Eric Matthes          22.97  https://amzn.to/2yQfQZl
   3  MySQL for Python                                                                  Albert Lukaszewski    49.99

最后,让我们关闭连接:

# close the cursor
cursor.close()
# close the DB connection
db_connection.close()

结论

有了它,MySQL 连接器库使 Python 开发人员可以方便地执行 SQL 命令,你可以对其他命令(如UPDATE和DELETE )执行相同的过程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: