带有 SQL 通配符和 LIKE 的 Python 字符串格式

发布于 2024-09-07 17:51:29 字数 1384 浏览 7 评论 0原文

我很难在 python 中获取一些 sql 来正确地通过 MySQLdb。 python 的字符串格式化让我很烦恼。

我的 sql 语句使用带有通配符的 LIKE 关键字。我在 Python 中尝试了很多不同的东西。问题是,一旦我让其中一个工作起来,MySQLdb 中有一行代码会在字符串格式上打嗝。

尝试1:

“选择 tag.userId,count(user.id) 作为用户 INNER JOIN 的总行数 tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (查询)

这是不行的。我得到值错误:

ValueError:索引 128 处不支持格式字符 ''' (0x27)

尝试 2:

“选择 tag.userId,count(user.id) 作为用户 INNER JOIN 的总行数 标签 ON user.id = tag.userId WHERE user.username LIKE '\%%s\%'" % (查询)

我从尝试 1 中得到相同的结果。

尝试 3:

like = "LIKE '%" + str(query) + "%'"totalq = "SELECT tag.userId, count(user.id) as TotalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username " + like

这正确地创建了totalq变量,但是现在当我去运行查询时,我从MySQLdb收到错误:

文件“build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py”,行 158、在执行 query = query % db.literal(args) 时出现 TypeError: 不够 格式字符串的参数

尝试 4 的参数:

like = "LIKE '\%" + str(query) + "\%'"totalq = "SELECT tag.userId, count(user.id) as TotalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username " + like

这与尝试 3 的输出相同。

这一切看起来都很奇怪。如何使用 python 在 sql 语句中使用通配符?

I'm having a hard time getting some sql in python to correctly go through MySQLdb. It's pythons string formatting that is killing me.

My sql statement is using the LIKE keyword with wildcards. I've tried a number of different things in Python. The problem is once I get one of them working, there's a line of code in MySQLdb that burps on string format.

Attempt 1:

"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN
tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (query)

This is a no go. I get value error:

ValueError: unsupported format character ''' (0x27) at index 128

Attempt 2:

"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN
tag ON user.id = tag.userId WHERE user.username LIKE '\%%s\%'" %
(query)

I get the same result from attempt 1.

Attempt 3:

like = "LIKE '%" + str(query) + "%'" totalq = "SELECT tag.userId,
count(user.id) as totalRows FROM user INNER JOIN tag ON user.id =
tag.userId WHERE user.username " + like

This correctly creates the totalq variable, but now when I go to run the query I get errors from MySQLdb:

File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line
158, in execute query = query % db.literal(args) TypeError: not enough
arguments for format string

Attempt 4:

like = "LIKE '\%" + str(query) + "\%'" totalq = "SELECT tag.userId,
count(user.id) as totalRows FROM user INNER JOIN tag ON user.id =
tag.userId WHERE user.username " + like

This is the same output as attempt 3.

This all seems really strange. How can I use wildcards in sql statements with python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

挽袖吟 2024-09-14 17:51:29

这些查询似乎都容易受到 SQL 注入攻击。

请尝试这样的操作:

curs.execute("""SELECT tag.userId, count(user.id) as totalRows 
                  FROM user 
            INNER JOIN tag ON user.id = tag.userId 
                 WHERE user.username LIKE %s""", ('%' + query + '%',))

其中有两个参数被传递给 execute()

Those queries all appear to be vulnerable to SQL injection attacks.

Try something like this instead:

curs.execute("""SELECT tag.userId, count(user.id) as totalRows 
                  FROM user 
            INNER JOIN tag ON user.id = tag.userId 
                 WHERE user.username LIKE %s""", ('%' + query + '%',))

Where there are two arguments being passed to execute().

凹づ凸ル 2024-09-14 17:51:29

要转义 Python 字符串格式化表达式中的 & 符号,请将 & 符号加倍:

'%%%s%%' % search_string

编辑: 但我绝对同意另一个答案。 SQL 查询中的直接字符串替换几乎总是一个坏主意。

To escape ampersands in Python string formatting expressions, double the ampersand:

'%%%s%%' % search_string

Edit: But I definitely agree with another answer. Direct string substitution in SQL queries is almost always a bad idea.

生生不灭 2024-09-14 17:51:29

这与字符串格式化无关,但问题是如何根据Python中的数据库操作要求执行查询(PEP 249

尝试这样的事情:

sql = "SELECT column FROM table WHERE col1=%s AND col2=%s" 
params = (col1_value, col2_value)
cursor.execute(sql, params)

这里是 psycog2 的一些示例,其中有一些对 mysql 也应该有效的解释(mysqldb 也遵循 PEP249 dba api 指南 2.0:这里是 mysqldb 的示例)

It's not about string formatting but the problem is how queries should be executed according to db operations requirements in Python (PEP 249)

try something like this:

sql = "SELECT column FROM table WHERE col1=%s AND col2=%s" 
params = (col1_value, col2_value)
cursor.execute(sql, params)

here are some examples for psycog2 where you have some explanations that should also be valid for mysql (mysqldb also follows PEP249 dba api guidance 2.0: here are examples for mysqldb)

谎言 2024-09-14 17:51:29
import mysql.connector
mydatabase = mysql.connector.connect(host="localhost", user="root", passwd="1234", database="databaseName")
mycursor = mydatabase.cursor()
user_input =[]
item = str("s%")
user_input.append(item)
mycursor.execute("SELECT * FROM employees WHERE FIRST_NAME LIKE %s ESCAPE ''",user_input )
result = mycursor.fetchall()
for row in enumerate(result):
    print(row)
import mysql.connector
mydatabase = mysql.connector.connect(host="localhost", user="root", passwd="1234", database="databaseName")
mycursor = mydatabase.cursor()
user_input =[]
item = str("s%")
user_input.append(item)
mycursor.execute("SELECT * FROM employees WHERE FIRST_NAME LIKE %s ESCAPE ''",user_input )
result = mycursor.fetchall()
for row in enumerate(result):
    print(row)
吾性傲以野 2024-09-14 17:51:29

我们可以尝试通过将百分比字符加倍来转义百分比字符,如下所示:

query_to_get_user_name = """ 
SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag 
ON user.id = tag.userId 
WHERE user.username LIKE '%%%s%%' """ % (user_name,) 

cursor.execute(query_to_get_user_name)

We could try escaping the percentage character by doubling them like this:

query_to_get_user_name = """ 
SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag 
ON user.id = tag.userId 
WHERE user.username LIKE '%%%s%%' """ % (user_name,) 

cursor.execute(query_to_get_user_name)
秋凉 2024-09-14 17:51:29

所以我尝试了这个,我想我已经得到了对我来说更容易理解的答案,一个学生。
在我的代码中,表名称是“books”,我正在搜索的列是“Name”。
如果您需要更多说明,请随时发送邮件至 [电子邮件受保护] 我会尽力尽快回答

def S():

        n=str(input('Enter the name of the book: '))

        name='%'+n+'%'

        NAME=name

        query="select * from books where Name like '"+NAME+"' "

        c.execute(query)

        ans=c.fetchall()
        
        if len(ans)>0:
            print('')

            for i in ans:

                print(i)

             print('')

        else:
            print('')

            print('An error occured')

            print('Name you gave does not exist :( ')

            print('')

So I tried this and I think I have got the answer which is simpler for me to understand , a school student .
In my code the table name is "books" and the column I'm Searching for is "Name".
If you need more xplaination , then feel free to drop a mail at [email protected] and I will try my best to answer ASAP

def S():

        n=str(input('Enter the name of the book: '))

        name='%'+n+'%'

        NAME=name

        query="select * from books where Name like '"+NAME+"' "

        c.execute(query)

        ans=c.fetchall()
        
        if len(ans)>0:
            print('')

            for i in ans:

                print(i)

             print('')

        else:
            print('')

            print('An error occured')

            print('Name you gave does not exist :( ')

            print('')
榕城若虚 2024-09-14 17:51:29

我使用了以下内容并且有效:

my_str = 'abc'
query = f"""select * from my_table where column_a like '%%{my_str}%%' """
df=pandas.read_sql_query(query, engine)

I used the following and it worked:

my_str = 'abc'
query = f"""select * from my_table where column_a like '%%{my_str}%%' """
df=pandas.read_sql_query(query, engine)
没企图 2024-09-14 17:51:29

我对你的问题有一个解决方案:

你不能使用:

"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (query)

你可以用字符串模板更改它,例如:

import MySQLdb
import string # string module
.......
value = {'user':'your value'}
sql_template = string.Template("""
SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN
tag ON user.id = tag.userId WHERE user.username LIKE '%$user%'
""")

sql = sql_template.substitute(value)

try:
    cursor.execute(sql)
    ...........
except:
    ...........
finally :
   db.close()

I have a solution to your problem :

You can not use :

"SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN tag ON user.id = tag.userId WHERE user.username LIKE '%%s%'" % (query)

you can change it with string template, such as :

import MySQLdb
import string # string module
.......
value = {'user':'your value'}
sql_template = string.Template("""
SELECT tag.userId, count(user.id) as totalRows FROM user INNER JOIN
tag ON user.id = tag.userId WHERE user.username LIKE '%$user%'
""")

sql = sql_template.substitute(value)

try:
    cursor.execute(sql)
    ...........
except:
    ...........
finally :
   db.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文