检查pyodbc中列中精确字符串的出现(频率)

时间:2017-07-19 13:42:23

标签: python sql pyodbc

所以我需要创建一个简单的函数来检查特定字符串' c'的出现次数。在一列中,然后除以总计。 Haven之前和pyodbc一起工作并且在一开始就陷入困境。

def get_c_i(c):
    cursor.execute('select count (*) from conditions')
    total = cursor.fetchone()[0]
    print(total)
    cursor.execute('select Name from Conditions where Name LIKE c')
    freq = cursor.fetchone()[0]
    print(freq)
    cursor.close()

Traceback (most recent call last):
  File "F:/Work/db/eyetoai/eyetoai/database/predict.py", line 34, in <module>
    get_c_i('Fibroadenoma')
  File "F:/Work/db/eyetoai/eyetoai/database/predict.py", line 27, in get_c_i
    cursor.execute('select Name from Conditions where Name LIKE c')
pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'c'. (207) (SQLExecDirectW)")

1 个答案:

答案 0 :(得分:1)

看起来你想要这样的东西:

cursor.execute("SELECT COUNT(*) FROM Conditions")
total = cursor.fetchval()
cursor.execute("SELECT COUNT(*) FROM Conditions WHERE Name=?", "c")
freq = cursor.fetchval()
print("{0} / {1} = {2}".format(freq, total, freq/total))  # check results