python 寫入資料時,連線資料庫時報錯ImportError: No module named MySQLdb
工具/原料
Python 2.7.7
python_mysql
方法/步驟
先去下載python_mysql.exe
官方地址:https://pypi.python.org/pypi/MySQL-python#downloads
我是用python_mysql 1.2.3,版本看您的需要
安裝python_mysql.exe時:軟體安裝時 找不到登錄檔
網上搜了一下 ,解決方法
{
import sys from _winreg import * # tweak as necessary version = sys.version[:3] installpath = sys.prefix regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version) installkey = "InstallPath" pythonkey = "PythonPath" pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % ( installpath, installpath, installpath ) def RegisterPy(): try: reg = OpenKey(HKEY_CURRENT_USER, regpath) except EnvironmentError as e: try: reg = CreateKey(HKEY_CURRENT_USER, regpath) SetValue(reg, installkey, REG_SZ, installpath) SetValue(reg, pythonkey, REG_SZ, pythonpath) CloseKey(reg) except: print "*** Unable to register!" return print "--- Python", version, "is now registered!" return if (QueryValue(reg, installkey) == installpath and QueryValue(reg, pythonkey) == pythonpath): CloseKey(reg) print "=== Python", version, "is already registered!" return CloseKey(reg) print "*** Unable to register!" print "*** You probably have another Python installation!"
}
啟動命令切到register.py檔案目錄下執行:
重啟安裝python_mysql就不會有這個錯誤
安裝完成 測試python_mysql 是否安裝成功
import MySQLdb
cmd 執行
沒有報錯說明安裝成功
測試資料庫是否連線成功,直接上程式碼:
#coding=utf-8import MySQLdb as mdbcon = mdb.connect( host = 'localhost', port = 3306, user = 'root', passwd = '123456', db = 'ceshi', charset='utf8')cur = con.cursor() #執行連結資料的命令
到這裡pythonan安裝python_mysql就結束