有时候需要在服务器上通过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])