无法使用 argparse 从 sqlite3 读取数据



我正在尝试创建一个模块来处理sqlite3。我的程序包含两部分:

  1. 基本程序
  2. 命令行接口(使用argparse(

这是我没有CLI的程序(它的工作(:

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.")

这是我的CLI部分:

# ------------------------------------ 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))

为了知道如何使用它,在你的终端中写下这个命令就足够了:

program -h

Program是我的python文件的名称。在我的数据库db.sqlite3中,我有一个服务器表,其中包含名称、密码和许可证。当我写:

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

我得到了:

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

请帮我解决这个问题。

由于read_query()是类属性,Python默认情况下会将对实例的引用传递到方法中。

为了解决这个问题,您需要提供一个包含引用的附加参数(通常称为self(,例如:

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

或者,由于您不需要自参考,请将其设为staticmethod,即:

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

相关内容

  • 没有找到相关文章

最新更新