MariaDB动态地将列添加到现有表

问题描述 投票:-1回答:1

我有一个python scrypt,它从网上查找数据。有时,这可能需要将新表添加到现有表中。我正在使用pymysql,我尝试了一些在网上找到的例子但不幸的是我一直遇到错误。似乎只是我的SQL查询有问题,但我不知道如何解决这个问题。

for j in range(1, counter + 1):
    if missing_matrix[j] !=  0:
        print("adding: ", missing_matrix[j])
        connection = create_engine('mysql+pymysql://user:pwd@server:3306/db').connect()
        print ('//////////////////// connected to mysql:')
        query = ("ALTER TABLE price_usd "
                "ADD IF NOT EXISTS new DOUBLE "
                "VALUES (%s)")
        query_data = (missing_matrix[j])
        connection.execute(query, query_data)

        connection.close()

return

一旦代码工作,我计划在整个迭代中进行一次连接。

添加后,该列将包含数值。

我得到的错误是整个报纸的红线,但这件作品看起来最值得注意:

sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'VALUES ('ballpoint pen')' at line 1") [SQL: 'ALTER TABLE price_usd ADD IF NOT EXISTS new DOUBLE VALUES (%s)'] [parameters: ('ballpoint pen',)]

python python-3.x mariadb mysql-python pymysql
1个回答
0
投票

我搞定了!

#   adding missing entities to mysql database
connection = create_engine('mysql+pymysql://user:pwd@server:3306/db').connect()
for j in range(1, counter + 1):
    if missing_matrix[j] !=  0:            
        query1 = ("ALTER TABLE price_usd ADD IF NOT EXISTS %s DOUBLE ") %(missing_matrix[j])
        connection.execute(query1)
Connection.close

我遇到的问题是我的列名在名称中有空格。我写了另一个用_替换这些空格的函数,然后它完美地工作了。

© www.soinside.com 2019 - 2024. All rights reserved.