Python MySQL – Insert Data Into a Table

摘要:在本教程中,您将学习如何使用 MySQL Connector/Python API 将数据插入表中。

要将新行插入 MySQL 表,请按照下列步骤操作:

  1. 通过创建新的MySQLConnection对象连接到 MySQL 数据库服务器
  2. MySQLConnection对象启动MySQLCursor对象。
  3. 执行INSERT语句向表中插入数据。
  4. 关闭数据库连接。

MySQL Connector/Python 提供的 API 允许您一次向表中插入一行或多行。让我们更详细地研究每种方法。

在表中插入一行

以下方法将一本新书插入books表中:

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config

def insert_book(title, isbn):
    query = "INSERT INTO books(title,isbn) " \
            "VALUES(%s,%s)"
    args = (title, isbn)

    try:
        db_config = read_db_config()
        conn = MySQLConnection(**db_config)

        cursor = conn.cursor()
        cursor.execute(query, args)

        if cursor.lastrowid:
            print('last insert id', cursor.lastrowid)
        else:
            print('last insert id not found')

        conn.commit()
    except Error as error:
        print(error)

    finally:
        cursor.close()
        conn.close()

def main():
   insert_book('A Sudden Light','9781439187036')

if __name__ == '__main__':
    main()Code language: Python (python)

在上面的代码中:

  • 首先,从 MySQL Connector/Python 包导入MySQLConnectionError对象,并从python_mysql_dbconfig 模块导入read_db_config()函数。
  • 接下来,定义一个名为insert_book()的新函数,它接受两个参数:title 和 isbn。在insert_book()函数内,构造一个INSERT语句( query )和数据( args )以插入到books表中。请注意,传递给函数的数据是一个元组。
  • 然后,创建一个新连接,执行该语句,并在try except块中提交更改。请注意,您必须显式调用commit()方法才能对数据库进行更改。如果成功插入新行,您可以使用MySQLCursor对象的lastrowid属性检索AUTO_INCREMENT 列最后插入 id
  • 之后,在insert_book()函数末尾关闭游标和数据库连接。
  • 最后,调用insert_book()函数将新行插入到main()函数中的books表中。

将多行插入表中

以下INSERT语句允许您将多行插入books表中:

INSERT INTO books(title,isbn)
VALUES('Harry Potter And The Order Of The Phoenix', '9780439358071'),
       ('Gone with the Wind', '9780446675536'),
       ('Pride and Prejudice (Modern Library Classics)', '9780679783268');Code language: SQL (Structured Query Language) (sql)

要将多行插入到Python中的表中,可以使用MySQLCursor对象的executemany()方法。请看下面的代码:

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config

def insert_books(books):
    query = "INSERT INTO books(title,isbn) " \
            "VALUES(%s,%s)"

    try:
        db_config = read_db_config()
        conn = MySQLConnection(**db_config)

        cursor = conn.cursor()
        cursor.executemany(query, books)

        conn.commit()
    except Error as e:
        print('Error:', e)

    finally:
        cursor.close()
        conn.close()

def main():
    books = [('Harry Potter And The Order Of The Phoenix', '9780439358071'),
             ('Gone with the Wind', '9780446675536'),
             ('Pride and Prejudice (Modern Library Classics)', '9780679783268')]
    insert_books(books)

if __name__ == '__main__':
    main()Code language: Python (python)

此示例中的逻辑与第一个示例中的逻辑类似。然而,我们不调用execute()方法,而是调用executemany()方法。

main()函数中,我们将一个元组列表传递给insert_books()函数,每个元组都包含书籍的标题和 isbn。

通过调用MySQLCursor对象的executemany()方法,MySQL Connector/Python 将INSERT语句转换为包含多个值列表的语句。

在本教程中,您学习了如何在 Python 中向表中插入一行或多行。

本教程有帮助吗?