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

Python操作MySQL數(shù)據(jù)庫的三種方法總結(jié)

 更新時間:2018年01月30日 10:33:14   作者:HP的博客  
下面小編就為大家分享一篇Python操作MySQL數(shù)據(jù)庫的三種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

1. MySQLdb 的使用

(1) 什么是MySQLdb?

MySQLdb 是用于 Python 連接 MySQL 數(shù)據(jù)庫的接口,它實現(xiàn)了 Python 數(shù)據(jù)庫 API 規(guī)范 V2.0,基于 MySQL C API 上建立的。

(2) 源碼安裝 MySQLdb: https://pypi.python.org/pypi/MySQL-python

$ tar zxvf MySQL-python-*.tar.gz
$ cd MySQL-python-*
$ python setup.py build
$ python setup.py install

(3) MySQLdb 的使用:

#!/usr/bin/env python
# coding=utf-8

import MySQLdb

def connectdb():
 print('連接到mysql服務(wù)器...')
 # 打開數(shù)據(jù)庫連接
 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要創(chuàng)建數(shù)據(jù)庫TESTDB,并在TESTDB數(shù)據(jù)庫中創(chuàng)建好表Student
 db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB")
 print('連接上了!')
 return db

def createtable(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # 如果存在表Sutdent先刪除
 cursor.execute("DROP TABLE IF EXISTS Student")
 sql = """CREATE TABLE Student (
   ID CHAR(10) NOT NULL,
   Name CHAR(8),
   Grade INT )"""

 # 創(chuàng)建Sutdent表
 cursor.execute(sql)

def insertdb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 插入語句
 sql = """INSERT INTO Student
   VALUES ('001', 'CZQ', 70),
    ('002', 'LHQ', 80),
    ('003', 'MQ', 90),
    ('004', 'WH', 80),
    ('005', 'HP', 70),
    ('006', 'YF', 66),
    ('007', 'TEST', 100)"""

 #sql = "INSERT INTO Student(ID, Name, Grade) \
 # VALUES ('%s', '%s', '%d')" % \
 # ('001', 'HP', 60)
 try:
  # 執(zhí)行sql語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  # Rollback in case there is any error
  print '插入數(shù)據(jù)失敗!'
  db.rollback()

def querydb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 查詢語句
 #sql = "SELECT * FROM Student \
 # WHERE Grade > '%d'" % (80)
 sql = "SELECT * FROM Student"
 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 獲取所有記錄列表
  results = cursor.fetchall()
  for row in results:
   ID = row[0]
   Name = row[1]
   Grade = row[2]
   # 打印結(jié)果
   print "ID: %s, Name: %s, Grade: %d" % \
    (ID, Name, Grade)
 except:
  print "Error: unable to fecth data"

def deletedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 刪除語句
 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交修改
  db.commit()
 except:
  print '刪除數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def updatedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 更新語句
 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  print '更新數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def closedb(db):
 db.close()

def main():
 db = connectdb() # 連接MySQL數(shù)據(jù)庫

 createtable(db)  # 創(chuàng)建表
 insertdb(db)  # 插入數(shù)據(jù)
 print '\n插入數(shù)據(jù)后:'
 querydb(db) 
 deletedb(db)  # 刪除數(shù)據(jù)
 print '\n刪除數(shù)據(jù)后:'
 querydb(db)
 updatedb(db)  # 更新數(shù)據(jù)
 print '\n更新數(shù)據(jù)后:'
 querydb(db)

 closedb(db)   # 關(guān)閉數(shù)據(jù)庫

if __name__ == '__main__':
 main()

運行結(jié)果:

2. PyMySQL 的使用

(1) 什么是 PyMySQL?

PyMySQL 是 Python 中用于連接 MySQL 服務(wù)器的一個庫,它遵循 Python 數(shù)據(jù)庫 API 規(guī)范 V2.0,并包含了 pure-Python MySQL 客戶端庫。

(2) 安裝 PyMysql:

pip install PyMysql

(3) 使用 PyMySQL:

#!/usr/bin/env python
# coding=utf-8

import pymysql

def connectdb():
 print('連接到mysql服務(wù)器...')
 # 打開數(shù)據(jù)庫連接
 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要創(chuàng)建數(shù)據(jù)庫TESTDB,并在TESTDB數(shù)據(jù)庫中創(chuàng)建好表Student
 db = pymysql.connect("localhost","hp","Hp12345.","TESTDB")
 print('連接上了!')
 return db

def createtable(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # 如果存在表Sutdent先刪除
 cursor.execute("DROP TABLE IF EXISTS Student")
 sql = """CREATE TABLE Student (
   ID CHAR(10) NOT NULL,
   Name CHAR(8),
   Grade INT )"""

 # 創(chuàng)建Sutdent表
 cursor.execute(sql)

def insertdb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 插入語句
 sql = """INSERT INTO Student
   VALUES ('001', 'CZQ', 70),
    ('002', 'LHQ', 80),
    ('003', 'MQ', 90),
    ('004', 'WH', 80),
    ('005', 'HP', 70),
    ('006', 'YF', 66),
    ('007', 'TEST', 100)"""

 #sql = "INSERT INTO Student(ID, Name, Grade) \
 # VALUES ('%s', '%s', '%d')" % \
 # ('001', 'HP', 60)
 try:
  # 執(zhí)行sql語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  # Rollback in case there is any error
  print '插入數(shù)據(jù)失敗!'
  db.rollback()

def querydb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 查詢語句
 #sql = "SELECT * FROM Student \
 # WHERE Grade > '%d'" % (80)
 sql = "SELECT * FROM Student"
 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 獲取所有記錄列表
  results = cursor.fetchall()
  for row in results:
   ID = row[0]
   Name = row[1]
   Grade = row[2]
   # 打印結(jié)果
   print "ID: %s, Name: %s, Grade: %d" % \
    (ID, Name, Grade)
 except:
  print "Error: unable to fecth data"

def deletedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 刪除語句
 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交修改
  db.commit()
 except:
  print '刪除數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def updatedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 更新語句
 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  print '更新數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def closedb(db):
 db.close()

def main():
 db = connectdb() # 連接MySQL數(shù)據(jù)庫

 createtable(db)  # 創(chuàng)建表
 insertdb(db)  # 插入數(shù)據(jù)
 print '\n插入數(shù)據(jù)后:'
 querydb(db) 
 deletedb(db)  # 刪除數(shù)據(jù)
 print '\n刪除數(shù)據(jù)后:'
 querydb(db)
 updatedb(db)  # 更新數(shù)據(jù)
 print '\n更新數(shù)據(jù)后:'
 querydb(db)

 closedb(db)   # 關(guān)閉數(shù)據(jù)庫

if __name__ == '__main__':
 main()

運行結(jié)果:

3. mysql.connector 的使用

(1) 什么是 mysql.connector?

由于 MySQL 服務(wù)器以獨立的進(jìn)程運行,并通過網(wǎng)絡(luò)對外服務(wù),所以,需要支持 Python 的 MySQL 驅(qū)動來連接到 MySQL 服務(wù)器。

目前,有兩個 MySQL 驅(qū)動:

mysql-connector-python:是 MySQL 官方的純 Python 驅(qū)動;

MySQL-python :是封裝了 MySQL C驅(qū)動的 Python 驅(qū)動。

(2) 安裝 mysql.connector:

pip install mysql-connector-python
pip install MySQL-python

(3) 使用 mysql.connector:

#!/usr/bin/env python
# coding=utf-8

import mysql.connector

def connectdb():
 print('連接到mysql服務(wù)器...')
 # 打開數(shù)據(jù)庫連接
 # 用戶名:hp, 密碼:Hp12345.,用戶名和密碼需要改成你自己的mysql用戶名和密碼,并且要創(chuàng)建數(shù)據(jù)庫TESTDB,并在TESTDB數(shù)據(jù)庫中創(chuàng)建好表Student
 db = mysql.connector.connect(user="hp", passwd="Hp12345.", database="TESTDB", use_unicode=True)
 print('連接上了!')
 return db

def createtable(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # 如果存在表Sutdent先刪除
 cursor.execute("DROP TABLE IF EXISTS Student")
 sql = """CREATE TABLE Student (
   ID CHAR(10) NOT NULL,
   Name CHAR(8),
   Grade INT )"""

 # 創(chuàng)建Sutdent表
 cursor.execute(sql)

def insertdb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 插入語句
 sql = """INSERT INTO Student
   VALUES ('001', 'CZQ', 70),
    ('002', 'LHQ', 80),
    ('003', 'MQ', 90),
    ('004', 'WH', 80),
    ('005', 'HP', 70),
    ('006', 'YF', 66),
    ('007', 'TEST', 100)"""

 #sql = "INSERT INTO Student(ID, Name, Grade) \
 # VALUES ('%s', '%s', '%d')" % \
 # ('001', 'HP', 60)
 try:
  # 執(zhí)行sql語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  # Rollback in case there is any error
  print '插入數(shù)據(jù)失敗!'
  db.rollback()

def querydb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 查詢語句
 #sql = "SELECT * FROM Student \
 # WHERE Grade > '%d'" % (80)
 sql = "SELECT * FROM Student"
 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 獲取所有記錄列表
  results = cursor.fetchall()
  for row in results:
   ID = row[0]
   Name = row[1]
   Grade = row[2]
   # 打印結(jié)果
   print "ID: %s, Name: %s, Grade: %d" % \
    (ID, Name, Grade)
 except:
  print "Error: unable to fecth data"

def deletedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 刪除語句
 sql = "DELETE FROM Student WHERE Grade = '%d'" % (100)

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交修改
  db.commit()
 except:
  print '刪除數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def updatedb(db):
 # 使用cursor()方法獲取操作游標(biāo) 
 cursor = db.cursor()

 # SQL 更新語句
 sql = "UPDATE Student SET Grade = Grade + 3 WHERE ID = '%s'" % ('003')

 try:
  # 執(zhí)行SQL語句
  cursor.execute(sql)
  # 提交到數(shù)據(jù)庫執(zhí)行
  db.commit()
 except:
  print '更新數(shù)據(jù)失敗!'
  # 發(fā)生錯誤時回滾
  db.rollback()

def closedb(db):
 db.close()

def main():
 db = connectdb() # 連接MySQL數(shù)據(jù)庫

 createtable(db)  # 創(chuàng)建表
 insertdb(db)  # 插入數(shù)據(jù)
 print '\n插入數(shù)據(jù)后:'
 querydb(db) 
 deletedb(db)  # 刪除數(shù)據(jù)
 print '\n刪除數(shù)據(jù)后:'
 querydb(db)
 updatedb(db)  # 更新數(shù)據(jù)
 print '\n更新數(shù)據(jù)后:'
 querydb(db)

 closedb(db)   # 關(guān)閉數(shù)據(jù)庫

if __name__ == '__main__':
 main()

運行結(jié)果:

以上這篇Python操作MySQL數(shù)據(jù)庫的三種方法總結(jié)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • python實現(xiàn)線程池的方法

    python實現(xiàn)線程池的方法

    這篇文章主要介紹了python實現(xiàn)線程池的方法,實例分析了Python線程池的原理與相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2015-06-06
  • pandas實現(xiàn)excel表格處理并讀取指定sheet的方法

    pandas實現(xiàn)excel表格處理并讀取指定sheet的方法

    這篇文章主要介紹了pandas實現(xiàn)excel表格處理并讀取指定sheet的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • python實現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr

    python實現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr

    這篇文章主要介紹了python實現(xiàn)將JPG、BMP圖片轉(zhuǎn)化為bgr方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Python中的pathlib.Path為什么不繼承str詳解

    Python中的pathlib.Path為什么不繼承str詳解

    這篇文章主要給大家介紹了關(guān)于Python中pathlib.Path為什么不繼承str的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • 檢測tensorflow是否使用gpu進(jìn)行計算的方式

    檢測tensorflow是否使用gpu進(jìn)行計算的方式

    今天小編就為大家分享一篇檢測tensorflow是否使用gpu進(jìn)行計算的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • 僅用50行代碼實現(xiàn)一個Python編寫的計算器的教程

    僅用50行代碼實現(xiàn)一個Python編寫的計算器的教程

    這篇文章主要介紹了僅用50行代碼實現(xiàn)一個Python編寫的計算器的教程,主要用到了PlyPlus庫使得核心代碼十分簡單,需要的朋友可以參考下
    2015-04-04
  • Python實現(xiàn)視頻畫質(zhì)增強的示例代碼

    Python實現(xiàn)視頻畫質(zhì)增強的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實現(xiàn)對視頻進(jìn)行畫質(zhì)增強功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以嘗試一下
    2022-04-04
  • python輸出國際象棋棋盤的實例分享

    python輸出國際象棋棋盤的實例分享

    在本篇文章里小編給大家整理的是一篇關(guān)于python輸出國際象棋棋盤的實例詳解,有興趣的朋友們可以參考下。
    2020-11-11
  • Python根據(jù)字符串調(diào)用函數(shù)過程解析

    Python根據(jù)字符串調(diào)用函數(shù)過程解析

    這篇文章主要介紹了Python根據(jù)字符串調(diào)用函數(shù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11
  • python基礎(chǔ)學(xué)習(xí)之生成器與文件系統(tǒng)知識總結(jié)

    python基礎(chǔ)學(xué)習(xí)之生成器與文件系統(tǒng)知識總結(jié)

    本文是參考《python數(shù)據(jù)分析》的附錄對生成器和文件系統(tǒng)結(jié)合案例的一個簡單回顧,文中對python生成器與文件系統(tǒng)作了非常詳細(xì)的介紹,對正在學(xué)習(xí)python的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05

最新評論