Python MySQL –插入操作详解

2021年3月9日16:17:08 发表评论 712 次浏览

MySQL是关系数据库管理系统(RDBMS), 而结构化查询语言(SQL)是用于使用命令(即从数据库创建, 插入, 更新和删除数据)处理RDBMS的语言。 SQL命令不区分大小写, 即CREATE和create表示同一命令。

注意:在将数据插入数据库之前, 我们需要创建一个表。为此, 请参阅PythonMySQL创建表。

插入资料

你可以一次插入一行或多行。连接器代码是将命令连接到特定数据库所必需的。

连接器查询

# Enter the server name in host
# followed by your user and
# password along with the database 
# name provided by you.
  
import mysql.connector
  
  
mydb = mysql.connector.connect(
   host = "localhost" , user = "username" , password = "password" , database = "database_name"
) 
  
mycursor = mydb.cursor()

现在插入查询可以写成如下:

例子:假设记录看起来像这样–

python-mysql-insert
sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"
val = ( "Ram" , "85" )
  
mycursor.execute(sql, val)
mydb.commit()
  
print (mycursor.rowcount, "details inserted" )
  
# disconnecting from server
mydb.close()

输出如下:

1 details inserted
python-mysql-insert-2

要一次插入多个值, executemany()使用方法。该方法遍历参数序列, 将当前参数传递给execute方法。

例子:

sql = "INSERT INTO Student (Name, Roll_no) VALUES (%s, %s)"
val = [( "Akash" , "98" ), ( "Neel" , "23" ), ( "Rohan" , "43" ), ( "Amit" , "87" ), ( "Anil" , "45" ), ( "Megha" , "55" ), ( "Sita" , "95" )]
  
mycursor.executemany(sql, val)
mydb.commit()
  
print (mycursor.rowcount, "details inserted" )
  
# disconnecting from server
mydb.close()

输出如下:

7 details inserted
python-mysql-insert-3

注意:

  • 的光标()用于迭代行。
  • 没有命令mydb.commit()更改将不会保存。

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: