1. 程式人生 > 實用技巧 >python--安裝、操作mysql資料庫

python--安裝、操作mysql資料庫

安裝

https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient網站下載對應版本的外掛

其中cp34對應python3.4,cp36對應python3.6,其他類推 若64位的不行可嘗試32位的

下載後執行:pip install D:\python3.8.3\Lib\site-packages\mysqlclient-1.4.6-cp38-cp38-win_amd64.whl(檔案路徑自己填)

查詢:

import MySQLdb
from readconfig import *  #讀取配置檔案.ini的py程式
class MysqlLib:
def __init__(self):
self.myhost=myhost  #myhost在readconfig內宣告
self.myuser=myuser  #myuser在readconfig內宣告
self.mypasswd=mypasswd  #mypasswd在readconfig內宣告
self.myport=myport  #myport在readconfig內宣告
self.mydb=mydb  #mydb在radconfig內宣告
#開啟資料庫連線
def __GetMysqlConnect(self): # 得到資料庫連線資訊函式, 返回: conn.cursor()
self.myconn=MySQLdb.connect(host=self.myhost,user=self.myuser,passwd=self.mypasswd,port=self.myport,db=self.mydb,charset='utf8')
mycur=self.myconn.cursor() #使用cursor()方法獲取遊標
if not mycur:
return (NameError, "mysql連線資料庫失敗")
else:
return mycur

def ExecMysqlQuery(self,sql):
mycur = self.__GetMysqlConnect() # 獲得資料庫連線資訊
#使用execure方法執行sql語句
try:
mycur.execute(sql)
# data=mycur.fetchone #使用fetchone()方法獲取一條資料
# data=mycur.fetchmany(x) #獲取x條記錄
data=mycur.fetchall() #獲取所有資料
except:
data="Error:mysql unable to fetch data"
# for ele in data:
# return list(ele)
self.myconn.close()
return data
#釋放資源
def ExecMysqlNonQuery(self, sql):
sqcur = self.__GetMysqlConnect()
sqcur.execute(sql)
self.myconn.commit()
self.myconn.close()


if __name__ == '__main__':
sql='select * from sys_role_category'
my=MysqlLib()
ss=my.ExecMysqlQuery(sql)
print(ss)