在Windows下用Python訪問MySQL資料庫,
並使用Flask開發API介面對外提供資料訪問。
1、查看 python 的版本 python -V
Python 2.7.12 :: Anaconda 4.1.1 (64-bit)
2、安裝驅動 MySQL-python,下載 python 的對應版本
https://pypi.python.org/pypi/MySQL-python/
3、檢查MySQLdb模組是否可以正常匯入
python
import MySQLdb
ImportError: DLL load failed: %1 不是有效 Win32 應用程式。
結論:驅動版本與python不對應,必須是32位對應32位,64位對應64位。
重新下載非安裝版本:MySQL-python-1.2.5.zip
解壓,進入MySQL-python-1.2.5目錄:
python setup.py install
報錯:error: Microsoft Visual C++ 9.0 is required (Unable to find vcvarsall.bat).
繼續下載:Microsoft Visual C++ Compiler for Python 2.7
http://www.microsoft.com/en-us/download/details.aspx?id=44266
安裝這個編譯器後,繼續安裝:
python setup.py install
繼續報錯:
_mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory
原因:關聯MySQL Connector的相關版本不一致造成的。
鬱悶,為啥還需要MySQL Connector。
太折騰,搜尋了一下,非官網上,有64位的MySQL-python下載:
http://www.codegood.com/archives/129
安裝後,再測試:
python
import MySQLdb
ok了。
同事建議使用conda來管理Python開發環境 ,介紹如下:
Anaconda 提供一個管理工具 conda ,可以把 conda 看作是 pip + virtualenv + PVM (Python Version Manager) + 一些必要的底層庫,也就是一個更完整也更大的整合管理工具。如果只想用 conda ,可以下載簡化版的 Miniconda(https://conda.io/docs/install/quick.html#linux-miniconda-install) ,需要 Anaconda 可以安裝完全版,一共大概400M,用阿里雲伺服器從官方網站下載大概要6個小時,不過還好清華大學TUNA鏡像源:https://mirrors.tuna.tsinghua.edu.cn/anaconda/
4、安裝Flask
pip install flask
安裝後,再測試:
python
import flask
ok了。
5、代碼
sql.py
# -*- coding: UTF-8 -*-
'''
封裝類
'''
import MySQLdb
class MyTest(object):
'''
MyTest
''' def __init__(self, HOST, USER, PASSWD, DB, PORT):
self.conn = MySQLdb.connect(
host=HOST, user=USER, passwd=PASSWD, db=DB, port=PORT)
self.cur = self.conn.cursor()
def getdata(self, sql):
'''
getdata
'''
result = None
try:
count = self.cur.execute(sql)
info = self.cur.fetchmany(count)
result = []
for row in info:
result.append(row)
return result
except MySQLdb.Error, e:
return "Error:%s" % str(e)
finally:
# 能夠改變變數範圍的程式碼片段是 def、class、lamda
if self.cur:
self.cur.close()
self.conn.commit()
self.conn.close()
app.py
# coding:utf-8
'''
在Windows下用Python訪問MySQL資料庫,並使用Flask開發API介面對外提供資料訪問
'''
from sql import MyTest
from flask import Flask, jsonify
APP = Flask(__name__)
@APP.route('/test')
def test():
'''
路由測試
'''
host, user, passwd = '127.0.0.1', '****', '*****'
dbname, port = 'dbdemo', 800
instance = MyTest(host, user, passwd, dbname, port)
result = instance.getdata("select * from mytb limit 0,10")
if result is not None:
return jsonify(result)
else:
return "no data"
if __name__ == "__main__":
APP.run(host='0.0.0.0', port=7777, debug=True)
測試 http://127.0.0.1:7777/test
OK。