1. 程式人生 > 資料庫 >Python 解析pymysql模組操作資料庫的方法

Python 解析pymysql模組操作資料庫的方法

pymysql 是 python 用來操作MySQL的第三方庫,下面具體介紹和使用該庫的基本方法。

1.建立資料庫連線

通過 connect 函式中 parameter 引數 建立連線,連線成功返回Connection物件

import pymysql

#建立資料庫連線
connection = pymysql.connect(host = 'localhost',user = 'root',password = '123456',database = 'mydb',charset = 'utf8'
)
#print(connection)

pymysql.connect()函式中常用的連線引數有以下幾種:

  • host:資料庫主機名或者ip地址
  • port:埠號
  • user:資料庫的賬號
  • password 或 passwd:資料庫的密碼
  • database 或 db:資料庫的名字
  • charset:編碼方式

Connection物件的重要方法:

  • close() 關閉資料庫連線
  • commit() 提交資料庫事物
  • rollback() 回滾資料庫事務
  • cursor() 獲得 Cursor遊標物件

2.建立遊標

一個Cursor遊標物件,暫時儲存了SQL操作所影響到的資料,相同的資料庫連線建立的遊標所引起的資料變化,會馬上反應到同一連線中的其它遊標物件。但是不同資料庫連線中的遊標物件,是否能及時反映出來,則與資料庫事物管理有關。

Cursor物件基本方法和屬性:

execute(operation,[parameters])

執行一條SQL語句,operation時SQL語句,parameters是其引數。返回值是整數,表示執行SQL語句影響的行數

executemany(operation,[parameters])

批量執行SQL語句

callproc(procname,[parameters])

執行儲存過程,procname是儲存過程名

使用execute()和executemany()方法查詢後,通過以下提取方法提取結果集

fetchone()

從結果集當中返回一條記錄的序列,無則返回None

fetchmany([size=cursor.arraysize])

從結果集當中返回小於或等於size的記錄序列,無則返回空序列,size預設是整個遊標的行數

fetchall()

從結果集當中返回所有的行數

3.建立資料庫(這裡我使用的是NaviCat)

建立一個名為pydb的資料庫,表名為user,欄位name和userid

在這裡插入圖片描述

在這裡插入圖片描述

資料的查詢

#建立資料庫連線
connection = pymysql.connect(host = 'localhost',charset = 'utf8'
)
#print(connection)
try:
 #建立遊標物件
 with connection.cursor() as cursor:
  #執行SQL操作
  sql = 'select name,userid from user where userid >%(id)s'
  cursor.execute(sql,{'id':0})
  #提取資料集
  result_set = cursor.fetchall()
  for row in result_set:
   print('id:{0} - name:{1}'.format(row[1],row[0]))
  #遊標自動關閉
finally:
 #關閉連線
 connection.close()

資料插入

#資料增加
connection = pymysql.connect(host = 'localhost',charset = 'utf8'
)
try:
 with connection.cursor() as cursor:
  sql = 'insert into user (userid,name) values (%s,%s)'
  cursor.execute(sql,(3,'cc'))
  #affectcount = cursor.execute(sql,'cc'))
  #print('影響的資料行數:{0}'.format(affectcount))
  #提交資料庫事務
  connection.commit()
except pymysql.DatabaseError:
 #資料庫事務回滾
 connection.rollback()
finally:
 connection.close()

執行結果:

在這裡插入圖片描述

資料更新

#資料更新
connection = pymysql.connect(host = 'localhost',charset = 'utf8'
)
#print(connection)
try:
 with connection.cursor() as cursor:
  sql = 'update user set name = %s where userid > %s'
  cursor.execute(sql,('Tom',2))
  #提交事務
  connection.commit()
  print('更新成功')
except pymysql.DatabaseError as e:
 connection.rollback()
 print(e)
finally:
 connection.close()

執行結果:

在這裡插入圖片描述

資料刪除

#資料刪除
connection = pymysql.connect(host = 'localhost',charset = 'utf8'
        )
try:
 with connection.cursor() as cursor:
  sql = 'delete from user where userid = %s'
  cursor.execute(sql,(1))
  #提交事務
  connection.commit()
  print("刪除成功")
except pymysql.DatabaseError as e:
 connection.rollback()
 print(e)
finally:
 connection.close()

執行結果:

在這裡插入圖片描述

總的來說和java進行對比,在資料庫的連線 和對

資料集進行的處理上,python體現的非常簡潔,最主要易於使用和理解。人生苦短,我用python!

總結

以上所述是小編給大家介紹的Python 解析pymysql模組操作資料庫的方法,希望對大家有所幫助!