python pyodbc查询循环只返回一个结果

标签 python for-loop pyodbc

我已经包含了下面的代码。基本上,我有一个表(称为 forumPosts),其中包含列 user_idchildrencontentidchildrenforumPosts 的 id 字符串,它们是后续论坛帖子(我不负责将子帖子组织到与父帖子相同的表中)。该字符串的格式类似于 '["id1","id2",...]'

我的目标是生成一个如下所示的数据集:

parent_user_id,child_user_id_1,child_user_id_2,...

这里的问题是下面的代码只打印一个输出。为什么要这样做?感谢您的帮助。

import pyodbc


#connect to database, create db cursor
cnxn = pyodbc.connect('cnxnstring', autocommit=True)
cursor = cnxn.cursor()

for row in cursor.execute("select user_id,children from myTable where children!='[]' and user_id!='null'"):
    children=row[1].replace('"','').replace('[','').replace(']','').split(',')
    userid=row[0]
    for child in children:
        print cursor.execute("select user_id from myTable where id = ?",child).fetchone()

请求列的示例数据:

  id           |  user_id    |  children
hgjegh4pjbr44p | gd6v7134AUa | ["asdf34dfg3sdfq", "asdegh4pjbrxx3"]
asdegh4pjbrxx3 | xzf7134AUax | ["hgjegh4pjbr44p"]
hgjegh4pjbr44p | NULL        | []
asdf34dfg3sdfq | adfcv34skax | []

最佳答案

说明

使用提供的示例数据,输出为:

('adfcv34skax', )
None

由于存在前导空格,因此未返回 asdegh4pjbrxx3 ID 行。这可以通过将最后一个 print 行更改为:

来观察
print child

哪些输出:

asdf34dfg3sdfq
 asdegh4pjbrxx3
hgjegh4pjbr44p

'asdegh4pjbrxx3' 不等于'asdegh4pjbrxx3',后者返回空结果。

解决方案

children 赋值行替换为以下内容,以去除必要的字符和空格:

children=[child.strip('"[] ') for child in row[1].split(',')]

我认为使用单个 strip 调用的列表理解比嵌套的 replace 更具可读性。

或者,ast.literal_eval应该也可以工作:

children=ast.literal_eval(row[1])

关于python pyodbc查询循环只返回一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21585310/

相关文章:

python - 如何不改变 Python 中的嵌套列表?

python - Python 中唯一的对象列表不起作用

javascript - 使用 for 循环从 Javascript 函数返回多个值

python - Pygame 旋转射击

python - 受槽位限制,仅选择一次项目

c - 素数平均程序

python - pyodbc - 如何使用变量作为参数执行 select 语句

python - 使用 Python/pyodbc 插入 Access DB

python - 在 ubuntu docker 镜像上连接时,SQL Server 的 ODBC 驱动程序 13 无法在 pyodbc 上打开 lib

python - Python正则表达式匹配方括号内的数字列表