如何通过argv和python中的控制台将参数传递给mysql连接器?

我正在尝试将我的凭据传递给代码,而无需像这样直接存储它们

cnx = mysql.connector.connect(user=dbuser, password=dbpassword, host=dbhost, database=dbdatabase)

我的代码:

import mysql.connector as mdb
import sys

class App(object):
    def __init__(self, ip, user, pswd, db):
        self.ip = ip
        self.user = user
        self.pswd = pswd
        self.db = db

        print(sys.argv)

        con = mdb.connect(self.ip, self.user, self.pswd, self.db)

        with con:

            cur = con.cursor()
            print(con.is_connected())
            cur.close()


def main(argv):
    '''
    Usage: python yourPY.py databaseIP username password databaseTable
    '''
    ip = argv[1]
    user = argv[2]
    pswd = argv[3]
    db = argv[4]
    App(ip, user, pswd, db)


if __name__ == "__main__":
    main(sys.argv)

并且在将CD转到正确的方向并传递参数后,我得到了这个错误。

发射和传递参数

python whatisconection.py localhost root my_password my_database

错误:

['whatisconection.py', 'localhost', 'root', 'my_password', 'my_database']
Traceback (most recent call last):
  File "whatisconection.py", line 34, in <module>
    main(sys.argv)
  File "whatisconection.py", line 30, in main
    App(ip, user, pswd, db)
  File "whatisconection.py", line 13, in __init__
    con = mdb.connect(self.ip, self.user, self.pswd, self.db)
  File "/usr/lib/python3.8/site-packages/mysql/connector/__init__.py", line 264, in connect
    return CMySQLConnection(*args, **kwargs)
TypeError: __init__() takes 1 positional argument but 5 were given

I understand that my mdb.connect has some critical mistakes and I must use kwargs here like host = dbhost but this is exactly what I'm trying to escape.

下面是我尝试解决此问题的尝试,没有任何效果。我想念一些基本知识。

con = mdb.connect(ip = '%s', user = '%s', pswd = '%s', db = '%s') % (ip, user, pswd, db)

and some other ways like ip = self.ip or self.ip = ip that are too dumb to be true.

我不明白为什么它不起作用,请帮忙

评论
  • 一脸苍白i
    一脸苍白i 回复

    I'd recommend using the argparse library, which is part of the standard library so no installs are required.

    可以这样使用:

    import argparse
    
    parser = argparse.ArgumentParser("difference")
    parser.add_argument("path", help="Database path used.", type=str)
    parser.add_argument("--u", help="Username", type=str,
                        required=False, default="")
    arser.add_argument("--p", help="Password", type=str,
                        required=False, default="")
    parser.add_argument("--ip", help="IP. Default='127.0.0.1 '", type=str,
                        required=False, default="127.0.0.1")
    args = parser.parse_args()
    
    path = args.path
    username = args.user
    password = args.password
    ip = args.ip