【问题标题】:ValueError: MySQL identifier cannot be entirely numeric with Pandas to_sqlValueError: MySQL 标识符不能完全是 Pandas to_sql 的数字
【发布时间】:2015-06-02 02:18:53
【问题描述】:

我正在使用 pandas.to_sql 将数据写入现有的 MySQL 表。该代码已经在 crontab 作业中运行了数周,没有失败。

我开始收到以下错误:ValueError: MySQL identifier cannot be fully numeric

我的代码:

thisweek.to_sql(name='bs_reporting_weeklymetrics', con = cnx, flavor = 'mysql', if_exists = 'append', index=False)

如您所见,表名不是数字。

【问题讨论】:

    标签: python mysql python-2.7 pandas


    【解决方案1】:

    这是由 pandas 0.16.1 中的更新引起的,我之前使用的是以前的版本(我认为是 0.14.XX)编辑:这将在 pandas 0.16.2 中修复

    随着此次更新,io.sql 包中的 to_sql 有新代码,用于检查表名和所有列名中的数字字符:

    def _get_valid_mysql_name(name):
    # Filter for unquoted identifiers 
    # See http://dev.mysql.com/doc/refman/5.0/en/identifiers.html
    uname = _get_unicode_name(name)
    if not len(uname):
        raise ValueError("Empty table or column name specified")
    
    basere = r'[0-9,a-z,A-Z$_]'
    for c in uname:
        if not re.match(basere, c):
            if not (0x80 < ord(c) < 0xFFFF):
                raise ValueError("Invalid MySQL identifier '%s'" % uname)
    if not re.match(r'[^0-9]', uname):
        raise ValueError('MySQL identifier cannot be entirely numeric')
    
    return '`' + uname + '`'
    

    re.match(r'[0-9], uname) 如果 uname 值只是数字或以数字字符开头,则返回 None 。我认为这是一个错误,因为 MySQL 支持包含并以数字字符开头的列名(我有 '90DayTrailingAvgRevenue')

    您可以更新熊猫代码以使用:

    if re.match(r'[0-9][0-9]*$', uname):
    

    代替那条线。这会更改正则表达式以查找 1 个或多个数字字符和行尾,以便将整个名称限定为数字,而不仅仅是第一个字符。它也切换到正匹配而不是负匹配,所以我删除了'not'

    如果您不想弄乱 pandas 包,那么我建议您将列重命名为不以数字开头。

    【讨论】:

    • 你能在 github 上为此打开一个问题吗? github.com/pydata/pandas/issues
    • 顺便说一句,使用 flavor='mysql' 已被弃用,并将在未来的版本中删除。您必须开始使用 sqlalchemy 才能使用 to_sql
    • 谢谢@joris!我一直在推迟转换。我现在正在尝试转换为使用 SQLAlchemy,并且无法正确写入 sql(我能够使用 sqlalchemy 引擎和 raw_connection() 读取 SQL)希望获得有关最佳方法的任何指导。我正在打开另一个问题,找不到解决此问题的答案,完成后将链接它
    • 关于使用 to_sql 实现 sqlalchemy 的新问题:stackoverflow.com/questions/30631325/…
    • 顺便说一句,上述问题的修复将在 0.16.2 中(一两周内发布的错误修复版本),请参阅链接问题
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 2020-04-14
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2021-03-06
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多