python带参数mysql查询_Python MySQL参数查询动态表名称

I want to query MySQL tables using my python program. However, the tables that I want to query are the ones whose names are passed in as variables (parameters).

I tried something like this:

readTable_query = """SELECT * FROM %s"""

readTable_cursor.execute(readTable_query, (table_name))

The problem with this is that the dynamically generated SQL query is putting the table name in quotes, i.e. instead of generating a query like "SELECT * FROM products", its generating a query like "SELECT * FROM 'products'". This is causing my program to fail and throws errors. Is there a workaround?

I know I could concatenate the query but that would lead to a security risk of SQL injection.

Full code for reference:

import MySQLdb

table_name = 'products'

db_connection = MySQLdb.connect(host,user,passwd,db)

readTable_cursor = db_connection.cursor()

readTable_query = """SELECT * FROM %s"""

readTable_cursor.execute(readTable_query, (table_name))

解决方案

According to http://dev.mysql.com/doc/refman/5.0/en/identifiers.html , valid table names consist of the following characters. [0-9a-zA-Z_$] So, it shouldn't be hard to write your own validator:

import re

table_name_validator = re.compile(r'^[0-9a-zA-Z_\$]+$')

if not table_name_validator.match(table_name):

raise ValueError('Hey! No SQL injecting allowed!')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值