How to pass params to mysql connector via argv and console in python?

Viewed 71

I'm trying to pass my credentials into code without storing them directly like this

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

My code:

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)

And after cd-ing to proper direction and passing params Im getting this error.

Launching and passing params

python whatisconection.py localhost root my_password my_database

Error:

['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.

Below are my attempts at fixing this, nothing worked. I'm missing some fundamentals I guess.

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 can't grasp why it's not working, pls help

1 Answers

So, the solution was quite simple.

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

I stole the wrong answer from the internet and an article creator apparently didn't even check his own code. He had a lot of praising comments and likes, but the code was wrong. RIP my time.

Related