Sqlite 2 python使用python tempfile

时间:2012-05-01 22:01:08

标签: python sqlite temporary-files pysqlite

我正在使用存储为python tempfile的数据库从sqlite中遇到一些奇怪的行为。本质上,查询sqlite_master表工作正常,但查询另一个表返回:

DatabaseError: database disk image is malformed

源数据库存储为python tempfile:

ntf=tempfile.NamedTemporaryFile(suffix='.gdb')

以下是查询功能。

def sqliteQ(string,filename):
'''                                                                                                                                                                                                                              
    string= query string                                                                                                                                                                                                             
    filename= string file name                                                                                                                                                                                                       
    '''
    con=sqlite.connect(filename)
    c= con.cursor()
    c.execute(string)
    out=c.fetchall()
    c.close()
    return out

我能够成功查询数据库,如下所示:

sq=db.sqliteQ("select sql from sqlite_master where type='table' and name='managements'", gdb.name)
In [13]: sq
Out[13]: 'CREATE TABLE managements (path varchar(255), name varchar(255), data varchar(50000), date date, owner varchar(64), password varchar(64), prot text)'

但是以下内容会返回错误:

    In[14]: m=db.sqliteQ('select * from managements', gdb.name)
    41     con=sqlite.connect(filename)
     42     c= con.cursor()
---> 43     c.execute(string)
     44     out=c.fetchall()
     45     c.close()

/usr/lib/python2.7/dist-packages/sqlite/main.pyc in execute(self, SQL, *parms)
    242         if len(parms) == 0:
    243             # If there are no paramters, just execute the query.

--> 244             self.rs = self.con.db.execute(SQL)
    245         else:
    246             if len(parms) == 1 and \

DatabaseError: database disk image is malformed

我可以使用sqlite命令行工具成功运行两个查询。任何建议都会有所帮助。

彼得

更新

在使用tempfile时,我似乎只遇到此问题。我正在下载.zip文件并将随附的sqlite数据库读取到cStringIO并使用此函数写入tempfile

def tGDB (URLo):
    mem=io.StringIO(URLo.read())
    zf=zp.ZipFile(mem)
    ntf=tempfile.NamedTemporaryFile(suffix='.gdb')
    ntf.write(zf.read(zf.namelist()[0]))
    return ntf 

我想这可能表明从zip到tempfile的转换管道存在问题,但是第一个查询有效并且第二个查询无效,这很奇怪。

0 个答案:

没有答案