sqlite3.OperationalError:接近“%":语法错误? [英] sqlite3.OperationalError: near "%": syntax error?

查看:51
本文介绍了sqlite3.OperationalError:接近“%":语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误:sqlite3.OperationalError: near "%": syntax error当我尝试运行以下代码时.导入 sqlite3

I'm receiving the error: sqlite3.OperationalError: near "%": syntax error when I try to run the following code. import sqlite3

def getFromDB(DBname,table, url):
    conn = sqlite3.connect(DBname)
    cursor = conn.cursor()
    sql = '''SELECT * FROM %s WHERE URL=%s'''
    stuff = cursor.execute(sql, (table,url))
    stuff = stuff.fetchall()
    return stuff

url = 'http://www.examplesite.com/'
getFromDB('AuthorData.sqlite','forbes',url)

我在使用 %sSQL 查询中使用参数.感谢您的帮助!

I'm using parameters in my SQL query using %s. Thanks for the help!

推荐答案

一些想法:- 表名不能使用参数- 由于sql-injection,使用字符串格式不好

Some idea: - Using parameter is not available for table name - Using string format is not good because of sql-injection

首先,创建一个使表名安全的方法:

So first, create a method to make table name safe:

def escape_table_name(table):
    return '"%s"'.format(table.replace('"', '')

然后使用?作为参数完成带有转义表名称和参数的代码:

Then complete the code with escape table name and parameter using ? for parameter:

    sql = '''SELECT * FROM %s WHERE URL=?'''.format(escape_table_name(table))
    stuff = cursor.execute(sql, (url,))
    stuff = stuff.fetchall()

这篇关于sqlite3.OperationalError:接近“%":语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆