Executemany confusion

2019-08-24 04:09发布

Ok, so I have a function that selects certain rows in a sqlite database based on input from a plugin. I got the plugin to select and fetch rows when just one statement is involved, but since I want to add some flexibility to this, I tried making the function use executemany when encountering lists or tuples. Yet, despite all the things I have fiddled and changed, I a still unable to get this to work, either because the sqlite statement is treating each character in the string as a binding, or because there are too many bindings in the tuple. Here's the code I have so far:

    def readoffset(self,offset):
        vartype = type(name)
        print(vartype)
        if vartype == int:
            self.memcursor.execute('''select all id,matbefore,matafter,name,date 
                                   from main as main where id = ?''',[offset])
            undolist = self.memcursor.fetchall()
            print(undolist)
            return(undolist)
        elif vartype == tuple or list:
            print(vartype)
            self.memcursor.executemany('''select all id,matbefore,matafter,name,date 
                                       from main as main where name = (?)''', [offset])
            undolist = self.memcursor.fetchall()
            return(undolist)

2条回答
The star\"
2楼-- · 2019-08-24 04:11

I don't think you need executemany here.
Try something like this instead:

self.memcursor.execute('''SELECT id, matbefore, matafter, name, date 
                            FROM main 
                           WHERE name IN (%s)''' % 
                       ','.join('?'*len(offset)), (offset,))

Note that the string interpolation is done to place multiple placeholders into the query.

查看更多
劳资没心,怎么记你
3楼-- · 2019-08-24 04:26

Look at http://www.python.org/dev/peps/pep-0249/

Use of this method for an operation which produces one or more result sets constitutes undefined behavior, and the implementation is permitted

So, executemany can be used for INSERT's and UPDATE's but not for SELECT

You can try following code:

elif isinstance(offset, (tuple, list)):
    offsets=', '.join(offset)
    self.memcursor.execute('''select all id,matbefore,matafter,name,date 
                                       from main as main where name IN (?)''', [offsets])
查看更多
登录 后发表回答