简体   繁体   中英

How do I put a placeholder for a column name in mysql python connector?

so I know how to use %s but it doesn't appear to work for a column name. my aim here is to get a column name (a roll number here) and use that to find information (how many days they attended)

roll=input("enter roll no.: ")
c1.execute("select sum(%s) from attendance", ("" + roll + "",))
a=c1.fetchall()

the table looks like:

date       | 11b1 | 11b2 | 11b3 |......| 11b45 |
2020-12-01 | 1    |  0   |  1   |......|    1  |
2020-12-02 | 1    |  1   |  1   |......|    0  |
2020-12-03 | 0    |  1   |  1   |......|    1  |

this doesn't work and seems to give me a random value so how do I write that middle code? also why does the original code not give errors but still give an arbitrary seeming number?

I will assume you mean the columns_names ;

According to Python 3.8

By using f string ¹

roll = input("enter roll name.: ")
a = c1.execute(f"select sum({roll}) from attendance").fetchall()

The names of MySQL schema objects - tables, columns etc - can be interpolated using string formatting, by surrounding the placeholder with backticks ('`', ASCII 0x96). See MySQL Identifiers .

Using backticks prevents errors if the column name contains a space, or matches a keyword or reserved word.

However backticks do not protect against SQL injection. As the programmer, it's your responsibility to make sure that any column names coming from outside your program (for example, from user input) are verified as matching the column names in the table .

colname = 'roll'
sql = f"""SELECT sum(`{colname}`) FROM attendance"""
mycursor.execute(sql)

For values in INSERT or UPDATE statements, or WHERE clauses, DB-API parameter substitution should always be used.

colname = 'roll'
colvalue = 42
sql = f"""SELECT sum(`{colname}`) FROM attendance WHERE colvalue = %s"""
mycursor.execute(sql, (colvalue,))

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