如何从sqlit3写入python中的.txt文件

时间:2017-06-20 18:08:28

标签: python-2.7 tkinter sqlite

我对编程和python相对较新。 我正在为健身房构建这个应用程序,使用tkinter输入客户详细信息,我把它全部运行但我需要一种方法将客户的电话号码从sqlite3数据库中提取到txt文件。

这是后端脚本

import sqlite3

class database:
    def __init__(self,db):
        self.conn=sqlite3.connect(db)
        self.cur=self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS Customers (id INTEGER PRIMARY KEY, name text, Phone integer, gender text, DoB date )")
        self.conn.commit()

    def add(self,name,phone,gender,DoB):
        self.cur.execute("INSERT INTO Customers VALUES (NULL,?,?,?,?)",(name,phone,gender,DoB))
        self.conn.commit()

    def search(self,name="",phone="",DoB=""):
        self.cur.execute("SELECT * FROM Customers WHERE name=? OR phone=? OR DoB=?",(name,phone,DoB))
        rows=self.cur.fetchall()
        return rows

    def view(self):
        self.cur.execute("SELECT * FROM Customers")
        rows=self.cur.fetchall()
        return rows

    def delete(self,id):
        self.cur.execute("DELETE FROM Customers WHERE id=?",(id,))
        self.conn.commit()

    def edit(self,id,name,phone,gender,DoB):
        self.cur.execute("UPDATE Customers SET name=?,phone=?,gender=?,DoB=? WHERE id=?",(name,phone,gender,DoB,id))
        self.conn.commit()

    def __del__(self):
        self.conn.close()

这是前端脚本

from Tkinter import *
from backWM import database

database=database("customer.db")
#window.geometry("%dx%d" % (500, 300))

"""-------------------FUNCTIONS--------------------"""
def get_selected_row(event):
    global selected_tuple
    index=list1.curselection()[0]
    selected_tuple=list1.get(index)
    e2.delete(0,END)
    e2.insert(END,selected_tuple[1])
    e3.delete(0,END)
    e3.insert(END,selected_tuple[2])
    e4.delete(0,END)
    e4.insert(END,selected_tuple[4])

def add_command():
    database.add(name_text.get(),phone_text.get(),gender_text.get(),dob_text.get())
    list1.delete(0,END)
    list1.insert(END,(name_text.get(),phone_text.get(),gender_text.get(),dob_text.get()))
    e2.delete(0,END)
    e3.delete(0,END)
    e4.delete(0,END)

def search_command():
    list1.delete(0,END)
    for row in database.search(name_text.get(),phone_text.get(),dob_text.get()):
        list1.insert(END,row)

def delete_command():
    database.delete(selected_tuple[0])
    list1.delete(END,selected_tuple[0])
    e2.delete(0,END)
    e3.delete(0,END)
    e4.delete(0,END)

def view_command():
    list1.delete(0,END)
    for row in database.view():
        list1.insert(END,row)

def edit_command():
    database.edit(selected_tuple[0],name_text.get(),phone_text.get(),gender_text.get(),dob_text.get())
    e2.delete(0,END)
    e3.delete(0,END)
    e4.delete(0,END)

def set_list(event):
    """
    insert an edited line from the entry widget
    back into the listbox
    """
    try:
        index = list1.curselection()[0]
        # delete old listbox line
        list1.delete(index)
    except IndexError:
        index = END
    # insert edited item back into listbox1 at index
    list1.insert(index, name_text.get(),phone_text.get(),gender_text.get(),dob_text.get())

window=Tk()
window.wm_title("WhiteMountains Gym")
"""-------------------LABELS--------------------"""
l1=Label(window,text="CUSTOMER DETAILS")
l1.grid(row=0,column=1, columnspan=5)
l1.config(font=("Proggy", 30),width=20)

l2=Label(window,text="Name")
l2.grid(row=1,column=1)

l3=Label(window,text="Phone Number")
l3.grid(row=1,column=3)

l4=Label(window,text="D.O.B")
l4.grid(row=2,column=3)

"""-------------------ENTRY----------------"""
name_text=StringVar()
e2=Entry(window,textvariable=name_text)
e2.grid(row=1,column=2)
e2.config(width=30)
e2.bind('<<return>>', set_list)

phone_text=StringVar()
e3=Entry(window,textvariable=phone_text)
e3.grid(row=1,column=4)
e3.bind('<<return>>', set_list)

gender_text=StringVar()
gender_text.set('Gender')
choices=['Gender','Male','Female']
option=OptionMenu(window,gender_text,*choices)
option.grid(row=2,column=1,columnspan=2)
option.config(width=15)
option.bind('<<return>>', set_list)

dob_text=StringVar()
e4=Entry(window,textvariable=dob_text)
e4.grid(row=2,column=4)
e4.bind('<<return>>', set_list)
"""----------------------BUTTONS----------------"""
b1=Button(window,text="ADD",width=12,command=add_command)
b1.grid(row=1,column=6)

b2=Button(window,text="SEARCH",width=12,command=search_command)
b2.grid(row=2,column=6)

b3=Button(window,text="DELETE",width=12,command=delete_command)
b3.grid(row=3,column=6)

b4=Button(window,text="UPDATE",width=12,command=edit_command)
b4.grid(row=4,column=6)

b5=Button(window,text="VIEW ALL",width=12,command=view_command)
b5.grid(row=5,column=6)

b5=Button(window,text="CLOSE",width=12,command=window.destroy)
b5.grid(row=6,column=6)


"""----------------------LISTBOX----------------"""
list1=Listbox(window,height=20,width=70)
list1.grid(row=7,column=0,columnspan=4)

s1=Scrollbar(window)
s1.grid(row=3,column=4,rowspan=10)

list1.configure(yscrollcommand=s1.set)
s1.configure(command=list1.yview)

list1.bind('<<ListboxSelect>>',get_selected_row)




window.mainloop()

那么如何将输入到手机条目小部件中的每个新电话号码保存到txt文件,以便我只能访问电话号码

1 个答案:

答案 0 :(得分:0)

你可以这样做:

def write_to_text_file(self):
    self.cur.execute("SELECT phone FROM Customers")
    rows = self.cur.fetchall()
    with open('phone_numbers','ab') as fou:
        for row in rows:
            fou.write(row[0])
    return fou

每次插入记录时都要更新:

def add(self,name,phone,gender,DoB):
    self.cur.execute("INSERT INTO Customers VALUES (NULL,?,?,?,?)",(name,phone,gender,DoB))
    self.conn.commit()
    self.write_to_text_file(self)