于 2020 年 1 月 7 日更新
Insert 语句用于在 mysql 中插入记录。
语法: INSERT INTO <some table> (<some column names>) VALUES("<some values>");
示例 1:
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()sql = "insert into city VALUES(null, 'Mars City', 'MAC', 'MARC', 1233)"number_of_rows = cursor.execute(sql)db.commit() # you need to call commit() method to save# your changes to the databasedb.close()
该程序在城市表中插入一个新城市,注意对db.commit()的使用,该方法将您的更改保存到数据库中。
示例 2:
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()name = "Some new city"country_code = 'PSE'district = 'Someyork'population = 10008sql = "insert into city VALUES(null, '%s', '%s', '%s', %d)" % \(name, country_code , district, population)number_of_rows = cursor.execute(sql)db.commit()db.close()
请注意,在第 18 行中使用了反斜杠(\)字符。\字符用于将 python 语句拆分为多行。
插入多行
要在表中插入多行,请使用游标对象的executemany()方法。
语法: cursor_object.executemany(statement, arguments)
statement:包含要执行的查询的字符串。
arguments:一个包含要在insert语句中使用的值的序列。
让我们举个例子。
from __future__ import print_functionimport MySQLdb as mydb = my.connect(host="127.0.0.1",user="root",passwd="",db="world")cursor = db.cursor()name = "Some new city"country_code = 'SNC'district = 'Someyork'population = 10008data = [('city 1', 'MAC', 'distrct 1', 16822),('city 2', 'PSE', 'distrct 2', 15642),('city 3', 'ZWE', 'distrct 3', 11642),('city 4', 'USA', 'distrct 4', 14612),('city 5', 'USA', 'distrct 5', 17672),]sql = "insert into city(name, countrycode, district, population)VALUES(%s, %s, %s, %s)"number_of_rows = cursor.executemany(sql, data)db.commit()db.close()
在下一篇文章中,我们讨论如何处理错误。
