Rumah  >  Soal Jawab  >  teks badan

Menggunakan senarai rentetan dalam klausa MySQL IN python dengan parameter

Saya cuba menggunakan pertanyaan dalam dalam python. Tetapi saya mempunyai pengecualian yang berbeza untuk ini.

Percubaan pertama ialah:

query = """select keyword
               from keyword 
               where keyword in %(ids)s and country = %(country)s"""
cursor.execute(query, {'ids': tuple(ids), 'country': country})

Ia memberikan ralat berikut: Failedprocessing pyformat-parameters; Python“tuple”无法转换为 MySQL 类型

Percubaan kedua ialah:

str_keywords = ",".join(tuple("'" + str(i) + "'" for i in ids))

query = """select keyword
           from keyword 
           where keyword in (%s) and country = %s"""
cursor.execute(query, (str_keywords, country))

Ini tidak memberikan ralat tetapi tidak berfungsi.

Ada cadangan?

P粉523335026P粉523335026205 hari yang lalu390

membalas semua(2)saya akan balas

  • P粉809110129

    P粉8091101292024-03-28 20:14:43

    Anda boleh menggunakan tali f dengan tupel:

    ids = ('1,2,3','54','67')
    code = 'BR'
    query = f"""select keyword
               from keyword 
               where keyword in {ids} and country_code = {code}
               and brand_app is not null"""
    query

    Keluaran:

    "select keyword\n           from keyword \n           where keyword in ('1,2,3', '54', '67') and country_code = BR\n           and brand_app is not null"

    balas
    0
  • P粉057869348

    P粉0578693482024-03-28 13:21:14

    Cuba yang berikut:

    params = ",".join(["%s"] * len(ids))
    query = f"""select keyword
                   from keyword 
                   where keyword in ({params}) and country = %s"""
    cursor.execute(query, (*ids, country))
    

    Matlamat di sini adalah untuk ids 中的每个值构建一个 in (%s, %s, %s, ..., %s) 子句,其中包含一个 %s pemegang tempat.

    Ada beberapa perkara yang perlu diberi perhatian:

    • IN Mungkin terdapat had atas bilangan ruang letak dalam klausa. Lihat MySQL DALAM Had Bersyarat untuk butiran.
    • Dipanggil jika ids 为空,则此查询无效。您可能已经有一些逻辑来处理空 ids 列表的情况,或者您的代码可能永远不会在 ids kosong. Jika tidak, anda perlu bekerja pada kes itu.

    balas
    0
  • Batalbalas