📅  最后修改于: 2020-11-07 07:40:11             🧑  作者: Mango
您可以使用INSERT INTO语句将新行添加到MySQL的现有表中。在这种情况下,您需要指定表的名称,列名称和值(与列名称的顺序相同)。
以下是MySQL的INSERT INTO语句的语法。
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
以下查询将一条记录插入到名为EMPLOYEE的表中。
INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000);
您可以使用SELECT语句将插入操作后的表记录验证为-
mysql> select * from Employee;
+------------+-----------+------+------+--------+
| FIRST_NAME | LAST_NAME | AGE | SEX | INCOME |
+------------+-----------+------+------+--------+
| Mac | Mohan | 20| M | 2000 |
+------------+-----------+------+------+--------+
1 row in set (0.00 sec)
不必总是指定列名,如果您以表中列的相同顺序传递记录的值,则可以执行不带列名的SELECT语句,如下所示:
INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000);
execute()方法(在游标对象上调用)将查询作为参数并执行给定的查询。要插入数据,您需要将MySQL INSERT语句作为参数传递给它。
cursor.execute("""INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)""")
使用Python将数据插入MySQL中的表-
导入mysql.connector包。
使用mysql.connector.connect()方法创建连接对象,方法是将用户名,密码,主机(可选的默认值:localhost)和数据库(可选的)作为参数传递给它。
通过在上面创建的连接对象上调用cursor()方法来创建游标对象。
然后,通过将INSERT语句作为参数传递给execute()方法来执行该语句。
以下示例执行SQL INSERT语句以将记录插入EMPLOYEE表-
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Preparing SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Executing the SQL command
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
# Closing the connection
conn.close()
您还可以在MySQL的INSERT查询中使用“%s”代替值,并将值作为列表传递给它们,如下所示-
cursor.execute("""INSERT INTO EMPLOYEE VALUES ('Mac', 'Mohan', 20, 'M', 2000)""",
('Ramya', 'Ramapriya', 25, 'F', 5000))
以下示例将一条记录动态插入Employee表中。
import mysql.connector
#establishing the connection
conn = mysql.connector.connect(
user='root', password='password', host='127.0.0.1', database='mydb'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Preparing SQL query to INSERT a record into the database.
insert_stmt = (
"INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME)"
"VALUES (%s, %s, %s, %s, %s)"
)
data = ('Ramya', 'Ramapriya', 25, 'F', 5000)
try:
# Executing the SQL command
cursor.execute(insert_stmt, data)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
# Closing the connection
conn.close()
Data inserted