首先安装库
sudo pip3 install pymysql
网上搜一个操作类
class MysqlData:
def __init__(self, host="192.168.1.2", user="root", password="123456", database="tm", port=3306):
# 连接数据库
self.connection = pymysql.connect(host=host, user=user, password=password, database=database, port=port,
charset='utf8', cursorclass=pymysql.cursors.SSCursor)
def modify_data(self, sql, args=None):
"""
Args:
sql: sql语句
args: 接收格式化参数
Returns:
"""
try:
with self.connection:
with self.connection.cursor() as cursor:
# 执行sql语句
a = cursor.execute(sql, args=args)
if a :
print('修改成功!')
else:
print('修改失败!args', args)
# 提交sql语句
self.connection.commit()
except pymysql.err.MySQLError as _error:
raise _error
def get_data(self, sql, args=None, is_data=False):
"""
Args:
sql: sql语句
args: 接收格式化参数
is_data: 判断获取多条数据还是单个数据,默认获取单个数据
Returns:
"""
try:
with self.connection:
with self.connection.cursor() as cursor:
# 执行sql语句
cursor.execute(sql, args=args)
# 返回查询出的数据信息
return cursor.fetchall() if is_data else cursor.fetchone()
except pymysql.err.MySQLError as _error:
raise _error
def close(self):
self.connection.cursor().close()
self.connection.close()
然后具体使用示例
db = MysqlData(ip)
data = db.get_data("SELECT `number`,pin_code FROM access_pin;", [], True)
for info in data:
if info[1] != '123456':
# 调用更新修改方法:修改php的地址和手机号【更新某一行的若干列,并且逗号分割】
db.modify_data("UPDATE access_pin SET pin_code = '123456' WHERE `number` = %s", info[0] )
# 再次调用查询方法并打印出来
print(db.get_data("SELECT * FROM access_pin WHERE `number` = %s", info[0]))
db.close()
顺便给应用增加一个防重复启动吧
"""
*/5 * * * * python3 /test.py > /test.log
如上 crontab运行一个定时任务 进程里会有2条
所以增加 pid!=(curps-1) 判断,一般情况下不用
"""
def check_process(processName):
ps1=psutil.pids()
curps=os.getpid()
print("current pid = "+str(curps))
for pid in ps1:
cmdline=str(psutil.Process(pid).cmdline())
if cmdline.find(processName)>=0 and pid!=curps:
if pid!=(curps-1) and psutil.Process(pid).ppid()!=curps:
p=psutil.Process(curps)
if p and p.ppid()!=pid:
print("This is the second process "+str(pid))
return 1
return 0
最后放在启动处调用
if check_process('/processname'):
sys.exit(0)