使用 python psychopg2 获取数据库中包含特定字符串的所有变量的计数
Using python psychopg2 to get a count on all variables in the database that contain a specific string
我有一个列表,words = [word1, word2, word3, ...]
我想使用 sql 到 return 每个单词出现在 sql 文件的 A 列中的次数。我不知道如何将变量传递到我的 sql 查询中。任何帮助,将不胜感激!到目前为止,我的代码如下所示:
import psycopg2 as sql
for word in words
conn = sql.connect(**params)
c = conn.cursor()
#Create query and parameters to get usernames and ids
Query = """ SELECT COUNT(Column A) FROM file
WHERE Column A SIMILAR TO '% **VARIABLE WORD** %'
LIMIT 1000; """
try:
c.execute(Query)
except:
conn.commit()
print("Error in Query")
Result = c.fetchall()
此外,这个计算 return 单词出现的总次数还是只计算它出现在 A 列中的行数? (请问"the team won the game"return中的算一还是二?)
psycopg2 使用的可替换参数标志是“%s”,要在带有可替换参数的查询中使用普通的“%”,您需要将其加倍(即“%%”)。所以你的代码应该是这样的:
Query = """SELECT COUNT(Column_A) FROM file
WHERE Column_A SIMILAR TO '%%%s%%'
LIMIT 1000;"""
try:
c.execute(Query, word)
这应该return该词出现的行数,而不是该词在所有行中出现的总次数。
您的示例在使用的列名称中有一个 space;我已经替换了下划线,但如果列名称确实包含 space,则该名称应在该查询中用双引号引起来。
我有一个列表,words = [word1, word2, word3, ...] 我想使用 sql 到 return 每个单词出现在 sql 文件的 A 列中的次数。我不知道如何将变量传递到我的 sql 查询中。任何帮助,将不胜感激!到目前为止,我的代码如下所示:
import psycopg2 as sql
for word in words
conn = sql.connect(**params)
c = conn.cursor()
#Create query and parameters to get usernames and ids
Query = """ SELECT COUNT(Column A) FROM file
WHERE Column A SIMILAR TO '% **VARIABLE WORD** %'
LIMIT 1000; """
try:
c.execute(Query)
except:
conn.commit()
print("Error in Query")
Result = c.fetchall()
此外,这个计算 return 单词出现的总次数还是只计算它出现在 A 列中的行数? (请问"the team won the game"return中的算一还是二?)
psycopg2 使用的可替换参数标志是“%s”,要在带有可替换参数的查询中使用普通的“%”,您需要将其加倍(即“%%”)。所以你的代码应该是这样的:
Query = """SELECT COUNT(Column_A) FROM file
WHERE Column_A SIMILAR TO '%%%s%%'
LIMIT 1000;"""
try:
c.execute(Query, word)
这应该return该词出现的行数,而不是该词在所有行中出现的总次数。
您的示例在使用的列名称中有一个 space;我已经替换了下划线,但如果列名称确实包含 space,则该名称应在该查询中用双引号引起来。