ValueError:MySQL标识符不能完全是数字,Pandas to \u sq

2024-05-16 11:49:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas.to\u sql将数据写入现有的MySQL表。代码已经在crontab作业中运行了几个星期,没有失败。在

我开始得到以下错误:ValueError:MySQL标识符不能完全是数字

我的代码:

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

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


Tags: to数据代码namepandassqlbs错误
1条回答
网友
1楼 · 发布于 2024-05-16 11:49:45

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

有了这个更新,在io.sql正在检查表名和所有列名中是否有数字字符的to\u 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 + '`'

在重新匹配(r'[0-9],uname)如果uname值仅为数字或以数字字符开头,则返回为None。我认为这是一个bug,因为MySQL支持包含并以数字字符开头的列名(我有一个'90daytailingavgreventure')

您可以更新pandas代码以使用:

^{pr2}$

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

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

相关问题 更多 >