最近在访问月维度创建的数据库的表时,出现在同一个账户同一个SQL,出现在mysql客户端可调用,但是再python中显示表不存在:

一、问题解析
结合现象:客户端可以,python不可以,猜测是数字字符的全角/半角差异导致。因为手动执行时自动兼容,但是python有严格区分。
二、代码
python
config = {
'host': ' 你的主机',
'port': 你的端口号,
'user': '你的用户名',
'password': '你的密码',
'database': '你的数据库名',
'charset': 'utf8mb4',
'init_command': 'SET NAMES utf8mb4;'
}
def conn_mysql_and_query(table_prefix,mobile):
try:
conn = pymysql.connect(**config)
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 1. 验证连接信息(确认连对库)
cursor.execute("SELECT @@hostname, @@port, DATABASE(), USER()")
db_info = cursor.fetchone()
print("=== Python连接信息 ===")
print(f" 主机:{db_info['@@hostname']}")
print(f" 端口:{db_info['@@port']}")
print(f" 当前库:{db_info['DATABASE()']}")
print(f" 登录用户:{db_info['USER()']}")
# 2. 兼容大小写的表名查询(核心:手动统一表名大小写)
target_pattern = unicodedata.normalize('NFKC', table_prefix+get_first_day_yyyymm01())
# 转小写后匹配(适配Linux下表名小写的情况)
cursor.execute("""
SELECT TABLE_NAME
FROM information_schema.tables
WHERE table_schema = %s
AND LOWER(table_name) LIKE LOWER(%s)
""", (db_info['DATABASE()'], f"{target_pattern}%"))
tables = cursor.fetchall()
if not tables:
print(f"\n❌ 未找到 {target_pattern} 相关表")
else:
print(f"\n✅ 找到 {len(tables)} 个匹配表:")
real_table = tables[0]['TABLE_NAME']
for t in tables:
print(f" - {t['TABLE_NAME']}")
# 3. 用真实表名执行查询(避免表名错误)
real_table1 = table_prefix + get_first_day_yyyymm01()
sql = f"SELECT * FROM tnotice.`{real_table1}` where mobile = '{mobile}' order by create_time desc;"
print(sql)
cursor.execute(sql)
data = cursor.fetchall()
print(data)
print(f"\n✅ 从 {real_table} 查询到 {len(data)} 条数据:")
for row in data[:2]: # 只打印前2条,避免刷屏
print(row)
except pymysql.Error as e:
print(f"\n❌ 数据库错误:{e}")
print(f"错误码:{e.args[0]},错误信息:{e.args[1]}")
finally:
if 'conn' in locals() and conn.open:
cursor.close()
conn.close()
def get_first_day_yyyymm01():
"""
功能:获取当前月份第一天,
:return:返回YYYYMMDD格式的字符串,eg:20260201
"""
current_date = date.today()
first_day = date(current_date.year, current_date.month, 1)
return first_day.strftime("%Y%m%d")```
三、经验总结
书写sql时,务必切换为英文输入法(避免输入全角字符)
复制粘贴:从文档或其他条件,先检查是否有全角字符(可粘贴到记事本,看是否有宽数字/符号)
执行前可打印SQL语句,核对数字、符号是否为半角