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