欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python針對(duì)mysql數(shù)據(jù)庫(kù)的連接、查詢、更新、刪除操作示例

 更新時(shí)間:2019年09月11日 09:33:54   作者:cakincqm  
這篇文章主要介紹了python針對(duì)mysql數(shù)據(jù)庫(kù)的連接、查詢、更新、刪除操作,結(jié)合實(shí)例形式詳細(xì)分析了Python操作mysql數(shù)據(jù)庫(kù)的連接與增刪改查相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了python針對(duì)mysql數(shù)據(jù)庫(kù)的連接、查詢、更新、刪除操作。分享給大家供大家參考,具體如下:

連接

一 代碼

import pymysql
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","root","root","db_test01" )
# 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor
cursor = db.cursor()
# 使用 execute() 方法執(zhí)行 SQL 查詢 
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條數(shù)據(jù).
data = cursor.fetchone()
print ("Database version : %s " % data)
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()

二 運(yùn)行結(jié)果

py =======
Database version : 5.7.10-log

查詢

一 代碼

import pymysql
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","root","root","db_test01" )
# 使用cursor()方法獲取操作游標(biāo) 
cursor = db.cursor()
# SQL 查詢語(yǔ)句
sql = "SELECT * FROM EMPLOYEE \
    WHERE INCOME > '%d'" % (1000)
try:
  # 執(zhí)行SQL語(yǔ)句
  cursor.execute(sql)
  # 獲取所有記錄列表
  results = cursor.fetchall()
  for row in results:
   fname = row[0]
   lname = row[1]
   age = row[2]
   sex = row[3]
   income = row[4]
    # 打印結(jié)果
   print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
       (fname, lname, age, sex, income ))
except:
  print ("Error: unable to fetch data")
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()

二 運(yùn)行結(jié)果

fname=Mac,lname=Mohan,age=20,sex=M,income=2000

更新

一 代碼

import pymysql
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","root","root","db_test01" )
# 使用cursor()方法獲取操作游標(biāo) 
cursor = db.cursor()
# SQL 更新語(yǔ)句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
  # 執(zhí)行SQL語(yǔ)句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫(kù)執(zhí)行
  db.commit()
  print("update OK")
except:
  # 發(fā)生錯(cuò)誤時(shí)回滾
  db.rollback()
# 關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()

二 運(yùn)行結(jié)果

update OK

刪除

一 代碼

import pymysql
# 打開(kāi)數(shù)據(jù)庫(kù)連接
db = pymysql.connect("localhost","root","root","db_test01" )
# 使用cursor()方法獲取操作游標(biāo) 
cursor = db.cursor()
# SQL 刪除語(yǔ)句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
  # 執(zhí)行SQL語(yǔ)句
  cursor.execute(sql)
  # 提交修改
  db.commit()
  print("delete OK")         
except:
  # 發(fā)生錯(cuò)誤時(shí)回滾
  db.rollback()
# 關(guān)閉連接
db.close()

二 運(yùn)行結(jié)果

delete OK

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》、《Python數(shù)學(xué)運(yùn)算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門(mén)與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論