解决python 访问数据库出现表名不存在的情况

最近在访问月维度创建的数据库的表时,出现在同一个账户同一个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语句,核对数字、符号是否为半角
相关推荐
ZHOUPUYU5 小时前
PHP 8.3网关优化:我用JIT将QPS提升300%的真实踩坑录
开发语言·php
小高不会迪斯科9 小时前
CMU 15445学习心得(二) 内存管理及数据移动--数据库系统如何玩转内存
数据库·oracle
寻寻觅觅☆9 小时前
东华OJ-基础题-106-大整数相加(C++)
开发语言·c++·算法
YJlio10 小时前
1.7 通过 Sysinternals Live 在线运行工具:不下载也能用的“云端工具箱”
c语言·网络·python·数码相机·ios·django·iphone
e***89010 小时前
MySQL 8.0版本JDBC驱动Jar包
数据库·mysql·jar
l1t10 小时前
在wsl的python 3.14.3容器中使用databend包
开发语言·数据库·python·databend
赶路人儿10 小时前
Jsoniter(java版本)使用介绍
java·开发语言
ceclar12311 小时前
C++使用format
开发语言·c++·算法
山塘小鱼儿11 小时前
本地Ollama+Agent+LangGraph+LangSmith运行
python·langchain·ollama·langgraph·langsimth