添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
斯文的数据线  ·  03 ORA系列:ORA-00942 ...·  1 年前    · 
刀枪不入的红薯  ·  Spring @Value ...·  2 年前    · 
豪情万千的花生  ·  android - ...·  2 年前    · 

MySQL和MariaDB是关系型数据库引擎,是与Python一起使用的非常流行的系统。它们使用一个关系模型,用表来描述数据之间的关系。MySQL和MariaDB遵循的是客户-服务器关系。换句话说,数据库存在于一个服务器上。要对数据库进行修改,你要向服务器发送一个请求。该请求包含选择、更新或删除数据的各种SQL语句或指令。然后,服务器接受该请求,执行该操作,并将结果反馈给客户端。在本教程中,我们将看到如何使用Python连接到MariaDB来创建、读取、更新和删除数据。

创建数据库和表

为了开始,我们可以首先创建我们需要的数据库和表,以存储一些项目和任务。我们可以在数据库的命令行中直接开始。

添加一些样本数据

现在让我们以项目和任务的形式向数据库添加一些数据。这两个表通过我们在任务表上配置的外键相互关联。因此,任何时候我们添加新的任务,我们必须指定任务所 涉及 的项目的ID。这就是关系型数据库管理系统的工作方式。

MariaDB [projects]> 

查看数据库记录

从命令行中查看记录表明我们已经准备好从Python中开始使用这个数据库了。

MariaDB [projects]> 

使用Python连接到MySql

为了使用Python连接到MySQL,我们可以使用Python MySql连接器。它可以使用pip install mysql-connector-python 来安装。一旦它被安装,下面的代码显示了如何使用**connect()**函数来建立与数据库的连接。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
print(db)
<mysql.connector.connection.MySQLConnection object at 0x000002586BDF43A0>

使用游标来执行SQL查询

现在连接让我们可以访问游标(),这就是我们对所连接的数据库执行SQL查询的方法。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
cursor = db.cursor()
cursor.execute("select * from projects")

使用游标fetchall()获取记录

执行查询不会立即返回查询的结果。要访问查询的结果,我们可以使用**fetchall()**函数,如下图所示。当我们打印出这些结果时,我们可以看到我们已经手动输入到数据库中的两个项目。爽啊!

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
cursor = db.cursor()
cursor.execute("select * from projects")
project_records = cursor.fetchall()
print(project_records)
db.close()
[(1, 'Plant Lettuce', 'Move lettuces seedlings from nursery to garden'), (2, 'Lawn Care', 'Take care of various lawn tasks')]

函数中的数据库操作

我们想在 Python 中对数据库做哪些事情呢?我们希望能够查看所有的项目,查看所有的任务,添加一个新的项目,等等。我们可以把这些操作放在一个Python函数中,当我们想完成其中一个操作时,只需调用这个函数即可。下面是查看所有项目的函数。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def view_projects():
    cursor = db.cursor()
    cursor.execute("select * from projects")
    project_records = cursor.fetchall()
    print(project_records)
view_projects()
db.close()
[(1, 'Plant Lettuce', 'Move lettuces seedlings from nursery to garden'), (2, 'Lawn Care', 'Take care of various lawn tasks')]

查看所有任务

这个函数将显示数据库中的所有任务。

def view_tasks():
    cursor = db.cursor()
    cursor.execute("select * from tasks")
    task_records = cursor.fetchall()
    print(task_records)
view_tasks()
[(1, 1, 'Prepare row for Great Lakes Lettuce'),
 (2, 1, 'Prepare row for Lolla Rosa Lettuce'), 
(3, 2, 'Fertilize Lawn'), 
(4, 2, 'Mow the Lawn')]

这个函数插入一个新的项目和其相关的任务。这有点棘手,因为我们需要在同一个函数中插入两个表。每个项目都有一个标题和描述,所以我们使用**execute()来插入项目。然后,我们需要使用cursor.lastrowid来获取插入时使用的ID。这是需要的,这样当我们开始插入相关的任务时,我们就会使用与该任务相关的正确的项目ID。对于任务,我们接受一个我们需要为该项目做的任务的列表。然后我们用这些任务建立一个元组,并使用executemany()**函数来插入数据。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def insert_project(title, description, tasks):
    project_data = (title, description)
    cursor = db.cursor()
    cursor.execute('''
    insert into projects(title, description) values (%s, %s)
    ''', project_data)
    project_id = cursor.lastrowid
    tasks_data = []
    for description in tasks:
        task_data = (project_id, description)
        tasks_data.append(task_data)
    cursor.executemany('''
    insert into tasks(project_id, description) values (%s, %s)
    ''', tasks_data)
tasks = ["Go to store", "Buy Paint", "Start Painting"]
insert_project("Paint Shed", "New Coat Of Paint On Shed", tasks)
db.commit()
db.close()

现在我们可以回到view_projects()函数,看看我们刚刚插入的新项目是否成功。注意每个项目都有自己的唯一ID。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def view_projects():
    cursor = db.cursor()
    cursor.execute("select * from projects")
    project_records = cursor.fetchall()
    print(project_records)
view_projects()
db.close()
[(1, 'Plant Lettuce', 'Move lettuces seedlings from nursery to garden'), (2, 'Lawn Care', 'Take care of various lawn tasks'), (3, 'Paint Shed', 'New Coat Of Paint On Shed')]

对于查看所有相关的任务也是如此。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def view_tasks():
    cursor = db.cursor()
    cursor.execute("select * from tasks")
    task_records = cursor.fetchall()
    print(task_records)
view_tasks()
db.close()
[(1, 1, 'Prepare row for Great Lakes Lettuce'), 
(2, 1, 'Prepare row for Lolla Rosa Lettuce'), 
(3, 2, 'Fertilize Lawn'), 
(4, 2, 'Mow the Lawn'), 
(8, 3, 'Go to store'), 
(9, 3, 'Buy Paint'), 
(10, 3, 'Start Painting')]

带有变量的Python MySql查询

通过在查询中使用一个变量,我们可以查看特定的记录,而不是仅仅选择所有的记录。下面的函数让我们查看与给定项目ID相关的任务。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def view_project_tasks(id):
    cursor = db.cursor()
    cursor.execute("select * from tasks where project_id = %s", (id,))
    task_records = cursor.fetchall()
    print(task_records)
view_project_tasks(1)
view_project_tasks(2)
view_project_tasks(3)
db.close()
[(1, 1, 'Prepare row for Great Lakes Lettuce'), (2, 1, 'Prepare row for Lolla Rosa Lettuce')]
[(3, 2, 'Fertilize Lawn'), (4, 2, 'Mow the Lawn')]
[(8, 3, 'Go to store'), (9, 3, 'Buy Paint'), (10, 3, 'Start Painting')]

如何排列结果数据

你可能希望查询的结果以降序或升序出现。这可以通过在你的查询中使用 "order by "子句来实现。

def view_projects():
    cursor = db.cursor()
    cursor.execute("select * from projects order by title desc")
    project_records = cursor.fetchall()
    print(project_records)
view_projects()
[(1, 'Plant Lettuce', 'Move lettuces seedlings from nursery to garden'), (3, 'Paint Shed', 'New Coat Of Paint On Shed'), (2, 'Lawn Care', 'Take care of various lawn tasks')]
def view_projects():
    cursor = db.cursor()
    cursor.execute("select * from projects order by title asc")
    project_records = cursor.fetchall()
    print(project_records)
view_projects()
[(2, 'Lawn Care', 'Take care of various lawn tasks'), (3, 'Paint Shed', 'New Coat Of Paint On Shed'), (1, 'Plant Lettuce', 'Move lettuces seedlings from nursery to garden')]

更新一个记录

我们希望能够更新数据库中的一条记录。也许我们想改变一个项目的标题。我们可以在我们的Python代码中使用 "update "SQL命令来完成这个任务,像这样。

import mysql.connector as mysql
db = mysql.connect(
    host='localhost',
    user='root',
    password='',
    database='projects'
def update_project(title, id):
    cursor = db.cursor()
    cursor.execute("update projects set title = %s where project_id = %s", (title, id,))
update_project("Plant The Lettuce!", 1)
db.commit()
db.close()

这个第一个项目现在的标题是 "种植生菜!"而不是 "种植生菜"。

如何在Python中使用MySQL和MariaDB 摘要

  • MySql使用表来描述数据之间的关系
  • MySql在自己的服务器上运行
  • 这创造了一种客户/服务器关系
  • 为了向数据库发送请求,需要一个驱动程序
  • mysql-connector-python可用于此目的。
  • MySql不是SQL
  • MySql是一个RDBMS(关系型数据库管理系统)。
  • SQL是一种与RDBMS互动的查询语言
  • MySql是非常快速和容易使用的。
  • MySql可以扩展到非常大的用例
  • SQLalchemy可以作为MySql的ORM使用。
  • 分类:
    代码人生
    标签: