Python MySQL——在表中插入数据

原文:https://www.studytonight.com/python/python-mysql-insert-data-in-table

在本教程中,我们将学习如何使用 Python 在 MySQL 表中插入单行和多行

**要将数据插入到 MySQL 表中或者将数据添加到我们在之前的教程中创建的 MySQL 表中,我们将使用INSERT SQL 语句。

如果你是 SQL 新手,你应该先了解一下 SQL INSERT 语句

Python MySQL - INSERT数据

让我们看看基本语法使用INSERT INTO语句将数据插入到我们的表中:

INSERT INTO table_name (column_names) VALUES(data)

我们可以通过两种方式在表中插入数据:

  • 一次插入一个单排

  • 一次插入多行

在 MySQL 表中插入单行

在本节中,我们将看到在 MySQL 表中插入单行数据的代码示例:

我们将向我们在 Python MySQL - Create Table 教程中创建的学生表添加数据。

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "root",
    passwd = "himaniroot@99",
    database = "studytonight"
)

cursor = db.cursor()
## defining the Query
query ="INSERT INTO students(name, branch, address) VALUES (%s, %s,%s)"
## There is no need to insert the value of rollno 
## because in our table rollno is autoincremented #started from 1
## storing values in a variable
values = ("Sherlock", "CSE", "220 Baker Street, London")

## executing the query with values
cursor.execute(query, values)

## to make final output we have to run 
## the 'commit()' method of the database object
db.commit()

print(cursor.rowcount, "record inserted")

上述代码的输出将是:

插入了 1 条记录

在 MySQL 表中插入多行

在本节中,我们将看到在 MySQL 表中插入多行数据的代码示例。

要在表格中插入多行,使用executemany()方法。它以包含数据的元组列表作为第二个参数,以查询作为第一个参数。

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "root",
    passwd = "himaniroot@99",
    database = "studytonight"
)

cursor = db.cursor()
## defining the Query
query ="INSERT INTO students(Name, Branch,Address) VALUES (%s, %s, %s)"

## storing values in a variable
values = [
    ("Peter", "ME","Noida"),
    ("Amy", "CE","New Delhi"),
    ("Michael", "CSE","London")
]

## executing the query with values
cursor.executemany(query, values)

## to make final output we have to run 
## the 'commit()' method of the database object
db.commit()

print(cursor.rowcount, "records inserted")

如果这三行都输入成功,上述代码的输出将是:

插入了 3 条记录

因此,在本教程中,我们学习了如何在 Python 中将数据插入到 MySQL 表中。