Search code examples
pythonsqlitecmdcommand-line-interfaceargparse

Can't read data from sqlite3 using argparse


I am trying to create a module to handle sqlite3. My program contains two parts:

  1. Base Program
  2. Command Line Interface (using argparse)

This is my program without CLI (It's work):

import argparse
from sqlite3 import Error, connect
import os

class db_connector:
    def __init__(self, path):
        self.path = path

    def create_connection(self):
        connection = None
        if os.path.exists(self.path):
            try:
                connection = connect(self.path)
                print('Connected to db successfuly.')
            except Error as e:
                print(f'Fail to connecting, the error {e} occured.')
        else:
            print('The path is not exists.')


        return connection

    def execute_query(self, connection, query):
        cursor = connection.cursor()
        try:
            cursor.execute(query)
            connection.commit()
        except Error as r:
            print(f'Can\'t execue the query, error {r} occured.')

    def read_query(connection, query):
        cursor = connection.cursor()
        result = None
        try:
            cursor.execute(query)
            result = cursor.fetchall()
            return result
        except Error as e:
            print(f"Can't read data, error '{e}' occurred.")

And this is my CLI part:

# ------------------------------------ CLI ------------------------------------

parser = argparse.ArgumentParser(prog='db', description='SQLite DB handler')
parser.add_argument('-db', '--connection-path', action='store', type=str)
parser.add_argument('-x', '--execute-query', action='store', type=str, nargs=2)
parser.add_argument('-r', '--read-query', action='store', type=str, nargs=2)

args = parser.parse_args()

if args.connection_path != None:
    db = db_connector(args.connection_path)
    connection = db.create_connection()

if args.execute_query != None:
    db = db_connector(args.execute_query[0])
    connection = db.create_connection()
    query = args.execute_query[1]
    db.execute_query(connection, query)

if args.read_query != None: # Problem is here!!! 
    db = db_connector(args.read_query[0])
    connection = db.create_connection()
    query = args.read_query[1]
    print(db.read_query(connection, query))

For know how to use it, it's enough to write this command in your terminal:

program -h

Program is the name of my python file. In my database db.sqlite3 I have a servers table with name, password and license. When I write:

program -r db.sqlite3 "select * from servers"

I got:

Connected to db successfuly.
Traceback (most recent call last):
  File "G:\Programmng language\Python\Projects\ToDo\server\db.py", line 67, in <module>
    print(db.read_query(connection, query))
TypeError: read_query() takes 2 positional arguments but 3 were given

Please help me fix this problem.


Solution

  • Since read_query() is a class attribute, Python will by default pass in a reference to the instance into the method.

    In order to fix this, you need to either provide an additional argument that holds the reference (typically called self), e.g.:

        def read_query(self, connection, query):
        # ...
    

    or, alternatively, since you don't need the self-reference, make it a staticmethod, i.e.:

        @staticmethod
        def read_query(connection, query):
        # ...