1. 程式人生 > 資料庫 >python MysqlDb模組安裝及其使用詳解

python MysqlDb模組安裝及其使用詳解

python呼叫mysql資料庫通常通過mysqldb模組,簡單說下如何呼叫

1.安裝驅動

目前有兩個MySQL的驅動,我們可以選擇其中一個進行安裝:

1. MySQL-python:是封裝了MySQL C驅動的Python驅動;

2.mysql-connector-python:是MySQL官方的純Python驅動。

這裡使用MySQL-python驅動,即MySQLdb模組。

命令列安裝

pip install python-mysql

或者在pycharm包中安裝

原始碼安裝方式

訪問: http://www.lfd.uci.edu/~gohlke/pythonlibs/,下載MySQL_python-1.2.5-cp27-none-win_amd64.whl

將其拷貝到Python安裝目錄下的Scripts目錄下,在檔案位置開啟cmd,執行pip install MySQL_python-1.2.5-cp27-none-win_amd64.whl

驗證,python(command line)輸入import MySQLdb,沒報錯,說明安裝成功。

測試連線:

#!/usr/bin/python 
# -*- coding: UTF-8 -*-  
import MySQLdb  
# 連線資料庫      連線地址  賬號  密碼   資料庫   資料庫編碼  
db = MySQLdb.connect("localhost","root","123456","test",charset="utf8") 
 
# 使用cursor()方法獲取操作遊標 
cursor = db.cursor() 
 
# 使用execute方法執行SQL語句 
cursor.execute("SELECT VERSION()") 
 
# 使用 fetchone() 方法獲取一條資料庫。 
data = cursor.fetchone() 
 
print "Database version : %s " % data 
 
# 關閉資料庫連線 
db.close() 

示例1:

#!/usr/bin/python 
# coding=utf-8 
import MySQLdb 
import os,sys 
import json 
class MysqlDb(object): 
 
  def __init__(self): 
    self.host = "127.0.0.1" 
 
  @staticmethod 
  def get_connect(): 
    db = MySQLdb.connect(self.host,"mail_report","mailawst",charset="utf8") 
    return db 
 
  def get_mysql_info(self,start_time,end_time): 
    tmp = [] 
    db = self.get_connect() 
    sql = 'select send_time,mail_id,mail_addr,server_domain,server_ip,mail_status from real_mail_log where send_time > "%s" and send_time < "%s" limit 10;' % (start_time,end_time) 
    cursor = db.cursor() 
    cursor.execute(sql) 
    values = cursor.fetchall() 
    for i in values: 
      data = {} 
      data["send_time"] = str(i[0]) 
      data["mail_id"] = str(i[1]) 
      data["mail_addr"]= str(i[2]) 
      data["server_domain"] = str(i[3]) 
      data["server_ip"] = str(i[4]) 
      data["mail_status"]= str(i[5].encode('utf8'))   
      tmp.append(data) 
    data = json.dumps(tmp,ensure_ascii=False) 
    db.close() 
    return data 
 
def main(): 
  u = MysqlDb() 
  print u.get_mysql_info('2017-05-01 00:00:02','2017-05-01 00:50:03')  
if __name__ == '__main__': 
  main() 

示例2:

#!/usr/bin/python 
# -*- coding: UTF-8 -*-  
import MySQLdb 
 
# 開啟資料庫連線 
db = MySQLdb.connect("localhost","test") 
 
# 使用cursor()方法獲取操作遊標 
cursor = db.cursor() 
 
# SQL插入語句 
ins_sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME,AGE,SEX,INCOME) 
     VALUES ('yu','jie',20,'M',8000)""" 
 
ins_sql1 = 'insert into employee(first_name,last_name,age,sex,income) values (%s,%s,%s)' 
 
# SQL查詢語句 
sel_sql = 'select * from employee where first_name = %s' 
 
# SQL更新語句 
upd_sql = 'update employee set age = %s where sex = %s' 
 
# SQL刪除語句 
del_sql = 'delete from employee where first_name = %s' 
try: 
  # 執行sql語句 
  # insert 
  cursor.execute(ins_sql) 
  cursor.execute(ins_sql1,('xu','f',8000)) 
  # select 
  cursor.execute(sel_sql,('yu',)) 
  values = cursor.fetchall() 
  print values 
  # update 
  cursor.execute(upd_sql,(24,)) 
  # delete 
  cursor.execute(del_sql,)) 
 
  # 提交到資料庫執行 
  db.commit() 
except: 
  # 發生錯誤時回滾 
  db.rollback() 
 
# 關閉資料庫連線 
db.close() 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。