如何写SQL - where列象Python中的“东西%”?

问题描述 投票:0回答:1

我在寻找客户的SQL表谁的名字与我的输入开始和我有问题,写了“从开始”的逻辑,它工作正常时,其WHERE? =。我使用pyodbc并使用驱动程序ODBC驱动程序17为SQL Server

我见过很多答案类似的问题,但他们总是指使用代码%s,而当我尝试它不工作

我试着写LIKE“%”的许多不同的方式,但我无法找到任何的例子

我当前的代码是:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName = ?", Company, CustomerName)
    result = cursor.fetchall()
    for row in result:
      print (row)

客户名称VAR设置为“MIC”和结果应该是:

微软

微系统

等等..

谢谢

python pyodbc
1个回答
2
投票

您需要连接具有%通配符的参数。在MySQL中使用CONCAT()功能,SQL-Server,则使用+操作。

此外,在该占位符填充的参数应该是一个元组,而不是单独参数cursor.execute()

MySQL的:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName LIKE CONCAT(?, '%')", (Company, CustomerName))

SQL-服务器:

  cursor.execute("select CustomerName, CustomerNum From customer WHERE Company = ? AND CustomerName ? + '%'", (Company, CustomerName))
© www.soinside.com 2019 - 2024. All rights reserved.