ValueError:使用Pandas to_sql,MySQL标识符不能完全是数字

时间:2015-06-02 02:18:54

标签: python mysql python-2.7 pandas

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

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

我的代码:

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

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

1 个答案:

答案 0 :(得分:2)

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

通过此更新,to_sql的io.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&#39; [0-9],uname)如果uname值只是带有数字字符的数字OR STARTS,则返回None。我认为这是一个错误,因为MySQL支持包含数字字符并以数字字符开头的列名(我有#90; 90DayTrailingAvgRevenue&#39;)

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

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

取代该行。这会更改正则表达式以查找一个或多个数字字符和行尾,以便它将整个名称限定为数字而不仅仅是第一个字符。它也会切换为正匹配而不是负数,因此我删除了&#39; not&#39;

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

相关问题