数据库每天根据日期生成一张新的表如:test_table_20230101表中存在字段mobile记录客户联系电话
需要判断某几个客户在一段时间内是否有过联系记录有过一次记录即可,不用全部检索
方式一:使用shell脚本进行搜索
1、编辑数据库配置 mysql-opts
[client]
host=127.0.0.1
user=root
password=abc123123
port=3306
2、准备检索脚本 chenk.sh
#!/bin/bash
###############################################################################
# File Name:check.sh
# Version:V1.0
# Author:francis
###############################################################################
#数据库配置
DB_NAME="database"
MASTER_OPTS="./mysql-opts"
#起止时间
starttime=20230101
endtime=20230331
phone=$1 #联系方式,有脚本执行时指定
while [[ ${starttime} =< ${endtime} ]] #判断时间,进行循环
do
tablename=test_table_${starttime} #拼接表名
starttime=`date -d "+1 day $starttime" +%Y%m%d` #时间加1天
num=` mysql --defaults-file=${MASTER_OPTS} --database ${DB_NAME} -Ne "select count(*) from ${tablename} where mobile='${phone}';"` #查询数据库
if [[ ${num} > 0 ]];then #判断查询结果
echo "${tablename}表中有${phone}发送记录共${num}条"
exit 1 #有记录,则直接退出,不再继续检索
fi
done
echo "${phone}没有发送记录"
3、准备调用脚本 phone_check.sh
#!/bin/bash
###############################################################################
# File Name:phone_check.sh
# Version:V1.0
# Author:francis
###############################################################################
#定义联系人数据
phone=(1312345678 15123456789 17123456789 18123456789)
#循环数组内容,调用检索脚本
for i in ${phone[*]}
do
sh check.sh ${i}
done
方式二:使用python进行搜索
#!/usr/bin/python3
'''
File Name:phone_check.py
Version:V1.0
Author:francis
'''
import threading
import datetime
import pymysql
#定义多线程类
class checkphone(threading.Thread):
def __init__(self,phone):
threading.Thread.__init__(self)
self.phone=phone
def run(self):
print('starting check',self.phone)
check_phone(self.phone)
print('ending check',self.phone)
#定义检索方法
def check_phone(check_phone):
#数据库配置
mydb=pymysql.connect(
host="127.0.0.1",
user="root",
passwd="abc123123",
database='databases')
mycursor=mydb.cursor()
#数据检索
for j in table_name:
sql='select count(*) from '+j+' where mobile= '+check_phone
mycursor.execute(sql)
sqlresult=mycursor.fetchone()
if int(sqlresult[0]) > 0:
print('{0}表有{1}发送记录,共{2}条'.format(j,check_phone,int(sqlresult[0])))
break
else:
print(check_phone,'没有发送记录')
phone=['13123456789','15123456789','17123456789','18123456789']
#定义数据表列表
table_name=[]
table_time_str='20230101'
table_time=datetime.datetime(2023,1,1)
while int(table_time_str) <= 20230331:
name='test_table_'+table_time_str
table_name.append(name)
table_time=(table_time+datetime.timedelta(days=1))
table_time_str=table_time.strftime("%Y%m%d")
#多线程
thread1=checkphone(phone[0])
thread2=checkphone(phone[1])
thread3=checkphone(phone[2])
thread4=checkphone(phone[3])
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread1.join()
thread2.join()
thread3.join()
thread4.join()
print('check is over')