How can I call an SQL query function in Python?

Asked

Viewed 218 times

-1

Hello, I am creating an application for studies and a question has arisen. It is divided into 3 files, a main, a database and another app. In the main I put the main menu so that the user choose the option. In the database I made a connect and SQL query functions. In the app, is the logic itself and here I am the biggest doubt.

This is my database file.

import sqlite3
class WorkDB:
    def __init__ (self, arquivo):
        self.connection = sqlite3.connect('workdb.db')
        self.cursor = self.connection.cursor()
    
    def select(self):
        self.cursor.execute('SELECT * FROM employee')
        for line in self.cursor.fetchall():
            print(line)
    
    def insert(self, name_emp, age, document, job_title, salary):
        data = 'INSERT OR IGNORE INTO employee (name_emp, age, document, job_title, salary) VALUES (?, ?, ?, ?, ?)'
        self.cursor.execute(data, (name_emp, age, document, job_title, salary))
        self.connection.commit()
    def edit(self, job_title, salary, name_emp):
        data = 'UPDATE OR IGNORE employee SET job_title=?, salary=? WHERE name_emp=?'
        self.cursor.execute(data, (job_title, salary, name_emp))
        self.connection.commit()
    def delete(self, name_emp):
        data = 'DELETE FROM employee WHERE name_emp=?'
        self.cursor.execute(data, (name_emp))
        self.connection.commit()
    
    def end(self):
        self.cursor.close()
if __name__ == '__main__':
    table_employee = WorkDB('workdb.db')

App Code

import database
def listar():
    print(database.table_employee.select()

I’m sorry, don’t leave here, rs, tried several ways.

1 answer

0


Hello, you need to instantiate the class in your logic file, not in your module. Do so:

from database import WorkDB


wdb = WorkDB('workdb.db')
wdb.select()
  • Dude, that’s right, it worked with select. Now I’m breaking my head with Insert, to try to insert a new employee for example.

  • Share here what you are doing, and if you are returning a mistake.

  • Basically what I want is to do a CRUD, but in separate files, one with a main panel asking what action to want, register, edit, delete and query. The second with the logic of the queries in sqlite and the third with the logic of receiving the user by the main panel. I’ve rewritten my code several times, rs. but I’m having trouble referencing one or the other.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.