无法将 pandas 数据框中的列添加到 python 中的 mysql

Not able to add a column from a pandas data frame to mysql in python

我已经从 python 连接到 mysql,我可以使用 df.to_sql 命令将整个数据帧添加到 sql。当我 adding/updating 来自 pd.DataFrame 的单列时,无法 udate/add.

这里是关于数据集、结果的信息,

In [221]: result.shape
Out[221]: (226, 5)

In [223]: result.columns
Out[223]: Index([u'id', u'name', u'height', u'weight', u'categories'], dtype='object')

数据库中已有 table,其中包含除类别之外的所有列,因此我只需将列添加到 table。从这些,

Python MYSQL update statement

ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax

cursor.execute("ALTER TABLE content_detail ADD category VARCHAR(255)" % result["categories"])

这可以成功添加列,但所有值为 NULL, 当我尝试这个时

cursor.execute("ALTER TABLE content_detail ADD category=%s VARCHAR(255)" % result["categories"])

以以下错误结束

ProgrammingError                          Traceback (most recent call last)
    <ipython-input-227-ab21171eee50> in <module>()
    ----> 1 cur.execute("ALTER TABLE content_detail ADD category=%s VARCHAR(255)" % result["categories"])

/usr/lib/python2.7/dist-packages/mysql/connector/cursor.pyc in execute(self, operation, params, multi)
    505             self._executed = stmt
    506             try:
--> 507                 self._handle_result(self._connection.cmd_query(stmt))
    508             except errors.InterfaceError:
    509                 if self._connection._have_next_result:  # pylint: disable=W0212

/usr/lib/python2.7/dist-packages/mysql/connector/connection.pyc in cmd_query(self, query)
    720         if not isinstance(query, bytes):
    721             query = query.encode('utf-8')
--> 722         result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
    723 
    724         if self._have_next_result:

/usr/lib/python2.7/dist-packages/mysql/connector/connection.pyc in _handle_result(self, packet)
    638             return self._handle_eof(packet)
    639         elif packet[4] == 255:
--> 640             raise errors.get_exception(packet)
    641 
    642         # We have a text result set

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=0     corporate
1     corporate

我觉得我缺少一些数据类型,请帮我解决这个问题,谢谢。

您无法在一个步骤中将包含所有数据的列添加到 table。您必须至少使用两个单独的语句来首先执行 DDL (ALTER TABLE),然后再执行 DML(UPDATEINSERT ... ON DUPLICATE KEY UPDATE)。

这意味着添加具有NOT NULL约束的列需要三个步骤:

  1. 添加可为空的列
  2. 用每行中的值填充列
  3. NOT NULL 约束添加到列

或者,通过使用 "dummy" 默认值,您可以分两步完成(注意不要留下任何浮动的 "dummy" 值,或使用 meaningful/well-documented):

  1. 将列添加为 NOT NULL DEFAULT ''(或使用例如 0 作为数字类型)
  2. 用每行中的值填充列

您可以选择再次更改 table 以删除 DEFAULT 值。就我个人而言,我更喜欢第一种方法,因为它不会在你的 table 中引入无意义的值,而且如果第二步出现问题,它更有可能抛出错误。我 可能 当列适用于某个自然 DEFAULT 值时使用第二种方法,我计划将其保留在最终的 table 定义中。

此外,您没有正确地参数化您的查询;您应该将参数值传递给方法,而不是在方法调用中格式化字符串参数。换句话说:

cursor.execute("Query with %s, %s, ...", iterable_with_values)  # Do this!
cursor.execute("Query with %s, %s, ..." % iterable_with_values)  # NOT this!