pymysql单条插入数据和批量插入数据:
一、單條插入數(shù)據(jù):
?
#!/usr/bin/python3
?
import pymysql
?
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
?
# 使用cursor()方法獲取操作游標(biāo)?
cursor = db.cursor()
?
# SQL 插入語(yǔ)句 ?里面的數(shù)據(jù)類(lèi)型要對(duì)應(yīng)
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
? ? ? ?LAST_NAME, AGE, SEX, INCOME) \
? ? ? ?VALUES ('%s', '%s', ?%s, ?'%s', ?%s)" % \
? ? ? ?('Mac', 'Mohan', 20, 'M', 2000)
try:
? ?# 執(zhí)行sql語(yǔ)句
? ?cursor.execute(sql)
? ?# 執(zhí)行sql語(yǔ)句
? ?db.commit()
except:
? ?# 發(fā)生錯(cuò)誤時(shí)回滾
? ?db.rollback()
?
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
?
二、批量插入數(shù)據(jù):
#!/usr/bin/env python
# -*-encoding:utf-8-*-
?
import pymysql
?
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","root","123","testdb")
?
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = db.cursor()
?
# SQL 插入語(yǔ)句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
? ? ? ?LAST_NAME, AGE, SEX, INCOME) \
? ? ? ?VALUES (%s,%s,%s,%s,%s)"
# 區(qū)別與單條插入數(shù)據(jù),VALUES ('%s', '%s', ?%s, ?'%s', %s) 里面不用引號(hào)
?
val = (('li', 'si', 16, 'F', 1000),
? ? ? ?('Bruse', 'Jerry', 30, 'F', 3000),
? ? ? ?('Lee', 'Tomcat', 40, 'M', 4000),
? ? ? ?('zhang', 'san', 18, 'M', 1500))
try:
? ?# 執(zhí)行sql語(yǔ)句
? ?cursor.executemany(sql,val)
? ?# 提交到數(shù)據(jù)庫(kù)執(zhí)行
? ?db.commit()
except:
? ?# 如果發(fā)生錯(cuò)誤則回滾
? ?db.rollback()
?
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
?
————————————————
版權(quán)聲明:本文為CSDN博主「瓦雪子」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/ATOOHOO/article/details/88173151
總結(jié)
以上是生活随笔為你收集整理的pymysql单条插入数据和批量插入数据:的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: word怎么全选数字改字体(word怎么
- 下一篇: Python应用02--批量往Mysql