Python Forum
Can anyone Please help on fixing this python code to connect and save things on sqlit
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can anyone Please help on fixing this python code to connect and save things on sqlit
#1
import os, sys
import sqlite3
from enum import Enum

class Listkeeper(object):
    def __init__(self):
        self.file = str()
        for i in os.listdir("."):
            if i.endswith(".db"):
                self.file = i
        if len(self.file) == 0:
            name = self.get_string("Please enter list name", "Name")
            if str(name).endswith(".db"):
                self.file = name
            else:
                self.file = name + ".db"
        assert len(self.file) > 0
        if not os.path.exists(self.file):
            with open(self.file, 'w') as f:
                f.write('')

    def get_string(self, message, name="String", default=None, min_len=0, max_len=50):
        message += ": " if default is None else "[{}]: ".format(default)
        while True:
            try:
                line = input(message)
                if not line:
                    if default is not None:
                        return default
                    else:
                        raise ValueError("{} can not be empty".format(name))
                if min_len > len(line) or len(line) > max_len:
                    raise ValueError("{} length must between {} and {} characters".format(name, min_len, max_len))
                return line
            except ValueError as err:
                print(err)

    def select(self, default=None):
        if default:
            for i in enumerate(default, start=1):
                print("{}: {}".format(i[0], i[1].strip('\n')))
        while True:
            try:
                selection = self.get_string("Select option in (A)dd (D)elete (S)ave (Q)uit")
                if selection not in ('A', 'a', 'D', 'd', 'S', 's', 'Q', 'q'):
                    raise ValueError("{} is not a valid option".format(selection))
                else:
                    return selection
            except ValueError as err:
                print(err)

    def list_items(self, list):
        with open(list, 'r') as f:
            contents = f.readlines()
        return contents

    def add_item(self, list, value):
        list.append(value)
        return sorted(list)

    # def rm_item(self, list, index):
        # if index == 0:
            # return list
        # list.pop(index - 1)
        # return list

    # def save(self, file, list):
        # with open(file, 'w') as f:
            # f.flush()
            # for line in list:
                # f.write(line.strip('\n') + '\n')
		
    def open(self, list):
        self.connection = sqlite3.connect(list)

    def set(self, newname):
        self.connection = sqlite3.connect(newname)
        cursor = self.connection.cursor()
        sql_command = """
        CREATE TABLE thelist (
        item_number INTEGER PRIMARY KEY,
        item_name VARCHAR(20));"""
        cursor.execute(sql_command)
        self.connection.commit()

    def load(self, newname):
        items = []
        cursor = self.connection.cursor()
        cursor.execute("SELECT * FROM thelist")
        result = cursor.fetchall()
        for l in result:
            items.append(l[1])
        return items

   
    def add(self, item):
        cursor = self.connection.cursor()
        format_str = """INSERT INTO thelist (item_number, item_name) VALUES (NULL, "{list}");"""
        sql_command = format_str.format(list = item)
        cursor.execute(sql_command)
        self.connection.commit()

    def delete(self, item):
        cursor = self.connection.cursor()
        format_str = """DELETE FROM thelist WHERE item_name = "{list}";"""
        sql_command = format_str.format(list=item)
        cursor.execute(sql_command)
        self.connection.commit()

    def close(self):
        self.connection.close()		
class Actions(object):
    """State machine to manage input and output"""

    def __init__(self):
        # setup state info
        self.file = Files()
        # get the file name & contents
        names = self.file.fnames
        if self.file.fnames: # if there are files to choose from
            self.show_list(names)
            digit = get_integer("Load file number (or 0 for new file)",
                                minimum=0, maximum=len(names))
            if digit != 0: # chosen file is loaded
                self.file.open(names[digit-1])
                self.items = self.file.load(names[digit-1])
                if self.items:
                    self.current = State.main # start with items displayed
                    return
                else:
                    self.current = State.empty # start with empty notice

        # user chooses a new filename
        self.items = []
        newname = get_string("Choose filename",
                                minimum_length=2, maximum_length=80)
        if not newname.endswith(".db"):
            newname += ".db"
        self.file.name = newname
        self.file.set(newname)
        self.current = State.empty
class State(Enum):
    """List of the states the program can be in"""
    empty = 1    
    main = 2     
    add = 3      # add an item to the list
    delete = 4   # remove an item from the list
    quit = 5     # close the connection
    finished = 6 # only flags halt to main loop		


if __name__ == "__main__":
    managedList = Listkeeper()
    itemList = list(managedList.list_items(managedList.file))
    while True:
        select = managedList.select(itemList)
        if select in ('A', 'a'):
            item = managedList.get_string("Add item", "List item", default=None, min_len=2)
            itemList = managedList.add_item(itemList, item)
        if select in ('D', 'd'):
            itemIndex = int(managedList.get_string("Delete item number ( '0' to cancel)"))
            itemList = managedList.rm_item(itemList, itemIndex)
        if select in ('S', 's'):
            managedList.save(managedList.file, itemList)
        if select in ('Q', 'q'):
            if itemList != managedList.list_items(managedList.file):
                while True:
                    save = managedList.get_string("Quit without saving[y/n]?")
                    if save in ('Y', 'y'):
                        print("Changes have not been saved")
                        sys.exit()
                    else:
                        print("Changes have been saved")
                        managedList.save(managedList.file, itemList)
                        sys.exit()
            else:
                sys.exit()
Reply
#2
Please state full nature of problem,
what you have tried,
and post all error messages verbatim, entire output
Reply
#3
Thanks a lot for your help and advise but my issue was that the program would write a database file but the written file appears to be empty i don know if i'm missing any code eg what i was trying to do was to save the data that i enter in the program to the sq lite
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  connect sql by python using txt. file dawid294 2 380 Jan-12-2024, 08:54 PM
Last Post: deanhystad
  How to Connect to PostgreSQL Through Jump Server and SSH Tunnel using Python? nishans 1 845 Jan-02-2024, 10:37 AM
Last Post: khanzain
  python connect to mssql wailoonho 7 1,400 Dec-07-2023, 02:06 AM
Last Post: wailoonho
  how to save to multiple locations during save cubangt 1 509 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  Using Python to connect to an XML ? jehoshua 12 1,841 Jul-11-2023, 12:34 AM
Last Post: jehoshua
  (python) Can i get some help fixing a English to Morse translator? Pls AlexPython 7 1,539 Sep-12-2022, 02:55 AM
Last Post: AlexPython
  Trying to make a bot to connect on discord with Selenium Python johnsmith43 2 41,932 Mar-21-2022, 02:56 PM
Last Post: Cloudytechnical
  Can a variable equal 2 things? Extra 4 1,450 Jan-18-2022, 09:21 PM
Last Post: Extra
  Invalid syntax error - need help fixing calgk01 3 3,227 Feb-23-2021, 08:41 PM
Last Post: nilamo
  Unusual things to do with unittest/HTMLTestRunner AndyHolyer 0 2,103 Jul-29-2020, 02:43 PM
Last Post: AndyHolyer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020