Python MySQL –将数据插入表

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

要将新行插入到MySQL表中,请执行以下步骤:

  • 通过创建一个新的MySQLConnection对象连接到MySQL数据库服务器。

  • 从MySQLConnection对象初始化一个MySQLCursor对象。

  • 执行INSERT语句以将数据插入表中。

  • 关闭数据库连接。

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()

在上面的代码中:

  • 首先,从MySQL Connector / Python包导入MySQLConnection和Error对象,并从python_mysql_dbconfig模块导入read_db_config()函数。

  • 接下来,定义一个名为insert_book()的新函数,该函数接受两个参数:title和isbn。
    在insert_book()函数内部,构造一个INSERT语句(查询)和数据(args)以插入到books表中。
    请注意,传递给函数的数据是元组。

  • 然后,创建一个新连接,执行该语句,然后在tryexcept块中提交更改。
    请注意,必须显式调用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');

要将多个行插入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()

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

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

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

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

日期:2019-11-20 08:52:39 来源:oir作者:oir