首頁  >  文章  >  資料庫  >  如何在MySQL中插入Python物件?

如何在MySQL中插入Python物件?

WBOY
WBOY轉載
2023-08-24 14:05:051022瀏覽

如何在MySQL中插入Python物件?

假設伺服器上存在一個名為'test'的MySQL資料庫,也建立了一個名為employee的表。讓這個表有五個欄位:fname,lname,age,gender和salary。

假設我們想要將一個包含以下記錄資料的元組物件插入Msql資料庫中。

t1=('Steven', 'Assange', 21, 'M', 2001)

To establish an interface between MySQL and Python 3, you need to install the PyMySQL module. Then you can set up the connection using the following statements

import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","root","","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()

Next step 是 is to insert query using data in the tuple

sql="insert into employee values(%s,%s,%d,%s,%d)" %t1

現在,使用遊標物件的execute()方法執行此查詢

cursor.execute(sql)

如果您檢查員工表的內容,將會顯示新增了一個新記錄。

以上是如何在MySQL中插入Python物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除