有時候需要在服務器上通過python腳本操作數據庫,這時就有一個問題,linux上默認安裝的python2.7,但是沒有操作mysql腳本需要的相關模塊。
解決:
1、下載pip
wget https://bootstrap.pypa.io/get-pip.py
可以看到安裝文件被下載到了/root/script的目錄下
2、安裝pip
3、利用pip安裝操作數據庫的pymysql模塊
安裝好了之後,就可以用python腳本操作數據庫了。附上一個腳本
# -*- coding: utf-8 -*- import pymysql conn = pymysql.connect(host="ip",port=3307,user="root", passwd="123", db="db") cursor = conn.cursor() sql="select id,name_short from project where type in (15,17) " cursor.execute(sql) projects = cursor.fetchall() for project in projects: #切換到數據庫 sqlCustomer="use ssb_customer_"+str(project[0]) cursor.execute(sqlCustomer) sqlqueryDraft="select count(1) from ssb_r_draft_version" cursor.execute(sqlqueryDraft) draftCount = cursor.fetchall() if draftCount[0][0]>0: print(project[1])