如何在MySQL中插入Python物件?

WBOY
發布: 2023-08-24 14:05:05
轉載
1020 人瀏覽過

如何在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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!