部分整数上的SQLite匹配

时间:2018-03-03 08:08:40

标签: python regex sqlite conditional

我有以下代码:

sic_code = int(input("Filter by SIC code (1-4 digits)? Default is all: ")

# Connect to the database file
conn = sqlite3.connect(db)
c = conn.cursor()

sql = ("SELECT Name "
       "FROM stock_data "
       "WHERE SIC_Code = {sc}".format(sc=sic_code))

# Run SQL query
c.execute(sql)

以下是SIC代码在数据库中的外观。

enter image description here

理想情况下,无论用户是输入7,73,737还是7372,我都希望匹配7372.我已尝试从简单的查询开始匹配4位数代码,但我无法得到这个上班。查询不返回任何行。没有SIC查询,一切正常。

SIC列和用户输入变量都指定为整数。

提前感谢您的任何帮助。

2 个答案:

答案 0 :(得分:0)

您正在sqlite中寻找LIKE

您将%_LIKE运营商

一起使用

如果要匹配字符串的某些部分,请使用%,例如

h%将与hothell ...

匹配

h_t将与huthit ..

匹配

如果你想使用LIKE来匹配VARCHAR值,那么integer可以与LIKE一起使用integer,而不是VARCHAR。将它们存储为#input sic_code should be string sic_code = input("Filter by SIC code (1-4 digits)? Default is all: ") sic_code = sic_code + '%' #where SIC_code is stored as `VARCHAR` SELECT Name FROM stock_data WHERE SIC_Code LIKE {sc}".format(sc=sic_code) ,然后使用

CAST

OR

您可以使用#input sic_code should be string sic_code = input("Filter by SIC code (1-4 digits)? Default is all: ") sic_code = sic_code + '%' #where SIC_code is stored as `integer` SELECT Name FROM stock_data WHERE CAST(SIC_Code as TEXT) LIKE {sc}".format(sc=sic_code)

cast

*我没有使用public class Main { private static boolean stop; public static void main(String[] args) throws InterruptedException { new Thread(() -> { int i = 0; while (!stop) { i++; } }).start(); TimeUnit.SECONDS.sleep(1); stop = true; } } ,但请阅读文档。

答案 1 :(得分:0)

以上解决方案均不适合我。相反,我将SQL数据导回到pandas数据框并在那里应用了正则表达式。

感谢您的帮助。

此致 莱恩