简体   繁体   中英

MySQL syntax error when giving column name with parameter substitution

So, I am trying to create a sql statement in python that adds a column with a specific name to a table, but I am getting the error you see in the tittle.

Im currently using this code.

columnname = 'note'
cur.execute("ALTER TABLE my_table_name ADD COLUMN %s MEDIUMTEXT", (columnname,))

That should create a column in my_table_name named note but it gives me this error: MySQLdb._exceptions.ProgrammingError: (1064, "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 ''note' MEDIUMTEXT' at line 1")

Hope someone can point out what I am doing wrong? Thanks.

EDIT: I know I should use normal string interpolation. But I want to keep adding columns like, column1 then column2 then column3 if the other ones are already storing data.

You are trying to use SQL "bind variables", also known as parameter substitution, for a column name. You Can't Do That™, You must specify column names (and table names) directly in your SQL statement.

Use normal string interpolation to construct your statements. Try something like this:

columnname = 'note'
cur.execute(f"ALTER TABLE my_table_name ADD COLUMN {columname} MEDIUMTEXT")

Or if you're using old-timey Python 2, use this:

columnname = 'note'
cur.execute("ALTER TABLE my_table_name ADD COLUMN " + columname + " MEDIUMTEXT")

You can, obviously, do this in a loop of some kind.

(Careful: adding columns to tables with many rows can be time consuming. And, adding columns to get around a UNIQUE index restriction is a very strange way to design a table. Instead, maybe, use a column without a UNIQUE index.)

If your columname values come from an end user, you must validate them before you use them. Otherwise, cybercreeps.

XKCD 约翰尼掉落表

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM