python中的sqlite查询只使用对象

时间:2016-02-04 15:56:40

标签: python sqlite

首先......我在过去的几个月里对Python很陌生,直到现在它一直都很顺利。但是我被困在这里,我非常接近通过我的显示器砸我的头。

当我运行此脚本时,我只获取写入文件的最后一行数据,而我需要的是以类部分中的格式写入的所有数据行。

VOL_HOURS.db有多行但只有最后一行被写入。 这是我的剧本:

    from vlist import VLIST

import sqlite3
import decimal
import os
import sys
import uuid

VERSION = "oops"
DEVICE_SOFTWARE_VERSION = "OOPS"
FILENAME = "VHOURS.txt"
conn = sqlite3.connect("VOL_HOURS.db")






def fromVolunteers():
    conn = sqlite3.connect("VOL_HOURS.db")


with conn:

    cur = conn.cursor()
    cur.execute("SELECT BOB, DAVE, CAROL, ANDY, CARL, DANNY, CHERYL, CYNTHIA, TARA, SCOTT, ASHLEY, CRYSTAL FROM VOLUNTEERS")
    rows = cur.fetchall()




for row in rows:
    bob = row[0] 
    dave = row[1]
    carol = row[2]
    andy= row[3]
    carl = row[4]
    danny = row [5]
    cheryl = row [6]
    cynthia = row [7]
    tara = row [8]
    scott = row [9]
    ashley = row [10]
    crystal = row [11]



def main():
    fromVolunteers()
    testOutput = open(FILENAME, "w+")

    vlist = VLIST()
    vlist.setBob(bob)
    vlist.setDave(dave)
    vlist.setCarol(carol)
    vlist.setAndy(andy)
    vlist.setCarl(carl)
    vlist.setDanny(danny)
    vlist.setCheryl(cheryl)
    vlist.setCynthia(cynthia)
    vlist.setTara(tara)
    vlist.setScott(scott)
    vlist.setAshley(ashley)
    vlist.setCrystal(crystal)

    vlist.dump_object(testOutput)

    testOutput.flush()
    testOutput.close()
cur.close()
conn.close()

if __name__ == "__main__":
    sys.exit(main())

它来自的类文件是:

class VLIST:

    def __init__(self):
        self.bob = ""
        self.dave = ""
        self.carol = ""
        self.andy = ""
        self.carl = ""
        self.danny = ""
        self.cheryl = ""
        self.cynthia = ""
        self.tara = ""
        self.scott = ""
        self.ashley = ""
        self.crystal = ""

    def setBob(self,bob):
        self.bob = bob
        return

    def setDave(self,dave):
        self.dave = dave
        return

    def setCarol(self,carol):
        self.carol = carol
        return

    def setAndy(self,andy):
        self.andy = andy
        return

    def setCarl(self,carl):
        self.carl = carl
        return

    def setDanny(self,danny):
        self.danny = danny
        return

    def setCheryl(self,cheryl):
        self.cheryl = cheryl
        return

    def setCynthia(self,cynthia):
        self.cynthia = cynthia
        return

    def setTara(self,tara):
        self.tara = tara
        return

    def setScott(self,scott):
        self.scott = scott
        return

    def setAshley(self,ashley):
        self.ashley = ashley
        return

    def setCrystal(self,crystal):
        self.crystal = crystal
        return

    def dump_object(self,testOutput):
        testOutput.write("VLIST,"+self.bob+","+self.dave+","+self.carol+","+self.andy+","+self.carl+","+self.danny+","+self.cheryl+","+self.cynthia+","+self.tara+","+self.scott+","+self.ashley+","+self.crystal+","+"\n")
如果这令人困惑,我提前道歉,就像我说我对这一切都是新手。谢谢你的时间。

2 个答案:

答案 0 :(得分:0)

在迭代@Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false); int endMargin = MyApplication.getSharedContext().getResources().getDimensionPixelSize(R.dimen.chat_end_margin); int margin = MyApplication.getSharedContext().getResources().getDimensionPixelSize(R.dimen.chat_margin); if(viewType == TYPE1) { ViewGroup parentView = (ViewGroup)parent.getParent(); CardView.LayoutParams params = (CardView.LayoutParams) (parentView.getLayoutParams()); params.setMargins(endMargin,margin,margin,margin); v.setLayoutParams(params); } return new ViewHolder(v); } 内部,您只是覆盖变量for row in rows:bob等的先前值。因此,在迭代结束时,这些变量只有最后的价值。

dave中删除迭代。此函数应仅设置fromVolunteers()变量,并将迭代放在rows函数中:

main

答案 1 :(得分:0)

以下是您的代码的重构版本。如果不知道数据库模式,它包含的内容,或者有一个要测试的示例文件,这只是您可以做的事情的近似值。当您的VOLUNTEERS表继续添加或删除列时,您只需要更改代码顶部的COLUMNS元组以补偿更改。

import contextlib
import sqlite3


DATABASE = 'VOL_HOURS.db'
OUTPUT = 'VHOURS.nmf'
COLUMNS = ('BOB', 'DAVE', 'CAROL', 'ANDY', 'CARL', 'DANNY', 'CHERYL',
           'CYNTHIA', 'TARA', 'SCOTT', 'ASHLEY', 'CRYSTAL')


def main():
    with open(OUTPUT, 'w') as file:
        for row in from_volunteers():
            file.write(str(VolunteerList.new(row)))


def from_volunteers():
    with sqlite3.connect(DATABASE) as connection:
        with contextlib.closing(connection.cursor()) as cursor:
            query = 'SELECT {} FROM VOLUNTEERS'.format(', '.join(COLUMNS))
            cursor.execute(query)
            return cursor.fetchall()


class VolunteerList:

    @classmethod
    def new(cls, row):
        obj = cls()
        for key, value in zip(COLUMNS, row):
            obj[key] = value
        return obj

    def __init__(self):
        self.__data = [''] * len(COLUMNS)

    def __setitem__(self, key, value):
        self.__data[COLUMNS.index(key.upper())] = value

    def __str__(self):
        return ','.join(['VLIST'] + self.__data + ['\n'])


if __name__ == '__main__':
    main()