简体   繁体   English

使用Python 3从Mysql检索和选择二进制值

[英]Retrieving and selecting binary values from Mysql with Python 3

I'm trying to select data from one table, and perform a query on another table using the returned values from the first table. 我试图从一个表中选择数据,并使用从第一个表返回的值对另一个表执行查询。

Both tables are case-sensitive, and of type utf8-bin. 这两个表都区分大小写,并且类型为utf8-bin。

When I perform my first select, I am returned a tuple of binary values: 当我执行第一次选择时,我返回一个二进制值的元组:

query = """SELECT id FROM table1"""
results = (b'1234', b'2345', b'3456')

I'd then like to perform a query on table2 using the ids returned from table1: 然后,我想使用从table1返回的ID对table2执行查询:

query = """SELECT element FROM table2 WHERE id IN (%s) """ % results

Is this the right way to do this? 这是正确的方法吗?

You need to create the query so that it can be properly parameterized: 您需要创建查询,以便可以对其进行适当的参数化:

query = """SELECT element FROM table2 WHERE id IN (%s) """ % ",".join(['%s'] * len(results))

This will transform the query to: 这会将查询转换为:

query = """SELECT element FROM table2 WHERE id IN (%s,%s,%s) """

Then you can just pass query and results to the execute() (or appropriate) method so that results are properly parameterized. 然后,您可以仅将queryresults传递给execute() (或适当的)方法,以便正确地对results进行参数化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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