|
| 1 | +#!/usr/bin/python3 |
| 2 | + |
| 3 | +""" |
| 4 | +Module contains script that takes in an argument |
| 5 | +and displays all values in the states table of |
| 6 | +hbtn_0e_0_usa where name matches the argument. |
| 7 | +1-Create database if not exist |
| 8 | +2-populated db |
| 9 | +3-run script cat 0-select_states.sql | mysql -uroot -p |
| 10 | +4-run ./2-my_filter_states.py root root hbtn_0e_0_usa 'Arizona' |
| 11 | +""" |
| 12 | + |
| 13 | + |
| 14 | +def connect_db(host, port, user, passwd, db, **kwargs): |
| 15 | + """ |
| 16 | + Connect MySQLdb to a Database |
| 17 | +
|
| 18 | + Args: |
| 19 | + host(str or int): Database host to use |
| 20 | + post(int): DB port |
| 21 | + user(str): DB user to use |
| 22 | + passwd(str): DB user's password |
| 23 | + db(str): database name to connect to |
| 24 | +
|
| 25 | + Return: |
| 26 | + cur(cursor): cursor object |
| 27 | + """ |
| 28 | + try: |
| 29 | + db = MySQLdb.connect(host, port=port, user=user, passwd=passwd, db=db) |
| 30 | + except MySQLdb.Error as e: |
| 31 | + # print(e) |
| 32 | + pass |
| 33 | + |
| 34 | + # create cursor object |
| 35 | + cur = db.cursor() |
| 36 | + return cur, db |
| 37 | + |
| 38 | + |
| 39 | +def close_connection(*args): |
| 40 | + """ |
| 41 | + Make clean up. Close all opening connection |
| 42 | + eg: cursor |
| 43 | + """ |
| 44 | + for value in args: |
| 45 | + value.close() |
| 46 | + |
| 47 | + |
| 48 | +def print_data(datas): |
| 49 | + """ |
| 50 | + Helper function used to print data |
| 51 | + """ |
| 52 | + for data in datas: |
| 53 | + print(data) |
| 54 | + |
| 55 | + |
| 56 | +def filter_user_data(av): |
| 57 | + """ |
| 58 | + Get all states with a name matches the argument |
| 59 | + from the database using MySQLdb connector |
| 60 | +
|
| 61 | + Args: |
| 62 | + av: list of arguments |
| 63 | + """ |
| 64 | + # get connection credentials |
| 65 | + host = "localhost" |
| 66 | + port = 3306 |
| 67 | + user = av[0] |
| 68 | + passwd = av[1] |
| 69 | + db = av[2] |
| 70 | + search_param = av[3] |
| 71 | + |
| 72 | + # make connection to database |
| 73 | + cur, db = connect_db(host=host, port=port, user=user, passwd=passwd, db=db) |
| 74 | + |
| 75 | + # execute raw sql |
| 76 | + query = """SELECT * FROM states WHERE BINARY \ |
| 77 | + name=%s ORDER BY id ASC""" |
| 78 | + states = [] |
| 79 | + try: |
| 80 | + cur.execute(query, (search_param,)) |
| 81 | + states = cur.fetchall() |
| 82 | + except MySQLdb.Error as e: |
| 83 | + # print(e) |
| 84 | + pass |
| 85 | + close_connection(cur, db) |
| 86 | + return states |
| 87 | + |
| 88 | + |
| 89 | +if __name__ == "__main__": |
| 90 | + import MySQLdb |
| 91 | + from sys import argv |
| 92 | + |
| 93 | + av = argv[1:] |
| 94 | + data = filter_user_data(av) |
| 95 | + print_data(data) |
0 commit comments