Python MySQL插入操作


Python MySQL插入操作

1、向表中添加记录

  1. 该 INTO INSERT 语句用来记录添加到表。在python中,我们可以提到格式说明符(%s)来代替值。
    2.我们在游标的 execute() 方法中以元组的形式提供实际值

  2. 案例

import mysql.connector 
 
# 创建一个连接对象  
myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")
# 创建游标对象

cur = myconn.cursor()  
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  
  
#The row values are provided in the form of tuple   
val = ("John", 110, 25000.00, 201, "Newyork")  
  
try:  
    # 向表中插入数据  
    cur.execute(sql,val)  
  
    # 提交事务处理  
    myconn.commit()  
      
except:  
    myconn.rollback()  
  
print(cur.rowcount,"record inserted!")  
myconn.close()
  • 输出
1 record inserted!

2、插入(添加)多行记录

  1. 插入多行,我们也可以使用python脚本一次插入多行。多行作为各种元组的列表

  2. 列表的每个元素都被视为一个特定的行,而元组的每个元素都被视为一个特定的列值(属性)

  3. 示例

import mysql.connector  
         
myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB")  
   
cur = myconn.cursor()  
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  
val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of spain"),("Nick",104,90000.00,201,"Newyork")]  
      
try:  
    cur.executemany(sql,val)  
 
    myconn.commit()  
except:  
    myconn.rollback()  

print(cur.rowcount,"records inserted!")  
myconn.close()
  • 输出
3 records inserted!

3、行ID

  1. 在SQL中,特定行由插入标识表示,该标识称为行标识。

  2. 我们可以使用游标对象的属性 lastrowid 来获取最后插入的行id。

  3. 案例

import mysql.connector  
   
myconn = mysql.connector.connect(host="192.168.126.20", user="root", passwd="mysql", database="PythonDB") 

cur = myconn.cursor()  
      
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s, %s, %s, %s)"  
      
val = ("Mike",105,28000,202,"Guyana")  
      
try:  
    #inserting the values into the table  
    cur.execute(sql,val)  
  
    #commit the transaction   
    myconn.commit()  
      
    #getting rowid  
    print(cur.rowcount,"record inserted! id:",cur.lastrowid)  
  
except:  
    myconn.rollback()  
  
myconn.close()
  • 输出
1 record inserted! id: 0


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM