Python之MySQLdb


MySQLdb是用於Python鏈接Mysql數據庫的接口,它實現了Python數據庫API規范V2.0,基於MySql C API上建立的。

1. MySQLdb安裝

  (1)安裝Mysql,參考上篇博客數據庫之MySql

  (2)使用pip安裝MySQLdb:pip install MySQL-python

      但是安裝的時候會報錯:error: command 'C:\\Program Files\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

      下面推薦兩種方法進行解決:

       a. 下載Python-3.5及上版本擴展的mysql驅動:https://pypi.python.org/pypi/mysqlclient/1.3.10

           之后將下載后的*.whl文件跟pip.exe放在同個目錄(一般是在 ..\Python36\Scripts\ 里)

      然后用cmd命令進入到這個目錄執行PIP命令安裝:pip install mysqlclient-1.3.10-cp36-cp36m-win32.whl 

     b. 安裝pymysql代替:pip install pymysql 

注:以上安裝方法內容來自原文https://www.cnblogs.com/bu1tcat/p/8283742.html     

2. MySQLdb實例

#coding=utf-8

import sys
import MySQLdb as db
import csv

def parse_csv(csvfile):
    with open(csvfile, 'r') as pf:
        reader = csv.reader(pf, delimiter=',')
        header = next(reader)
        csvdata = []
        for row in reader:
            csvdata.append(row)
    return header, csvdata        
        
    
#鏈接數據庫
def mysqldb_operator(data):
    conn = db.connect(host="localhost", user="root", passwd="", db="xbqr", charset="utf8")
    print (conn)
    print ("datebase connect success!")
    curs = conn.cursor()
    #創建表之前先刪除表
    curs.execute("drop table IF EXISTS table_xbqr")
    conn.commit()
    #創建表
    query = "create table table_xbqr(\
        SupplierName VARCHAR(32),\
        InvoiceNumber VARCHAR(32),\
        PartNumber VARCHAR(32),\
        Cost VARCHAR(32),\
        PurchaseDate DATE)"
    curs.execute(query)
    conn.commit()
    for row in data:
        curs.execute("INSERT INTO table_xbqr VALUES(%s,%s,%s,%s,%s);", row)
        conn.commit()
    curs.execute("select * from table_xbqr")
    conn.commit()
    selectdata = curs.fetchall()
    print (selectdata)

if __name__ == "__main__":
    csvfile = sys.argv[1]
    print ("csv file name:", csvfile)
    header, data = parse_csv(csvfile)
    print ("header:")
    print (header)
    print ("csvdata:")
    print (data)
    mysqldb_operator(data)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM