I currently have 2 scripts test.py and connections.py. test.py is currently being used to just test code to be able to incorporate into other scripts. connections.py contains a set of functions to create a MySQL connection, close connection, and execute SQL statement.
The connections.py is to be used by multiple scripts that need to connect to the database. I know how to call the appropriate function when within the same script and I know how to call a function in another script when there is only one function in the script.
What I can’t figure out is how to call the right function when there are multiple functions. Through google/stackoverflow all the examples I have found are when there is only one function or the call is being made in the same script.
I have tried using a class with functions in it and just a file with functions. Code below is without class. Any help is greatly appreciated. I am also using python 3.5 on windows 10 and it will eventually be moved to a UNIX machine if that makes any difference.
import connections as c sql = "select * from tbl" sqlRec = c.select_stmt(sql) # this is the command I need help with print(sqlRec)
import mysql.connector as MySQL def connection(): #set up connection con = MySQL.connect(user='xxx',password='xxx',host='xxx',db='xxx') cursor = con.cursor() return con, cursor def close_connection(cursor,conn): cursor.close() con.close() def select_stmt(sql): con, cursor = connection() cursor.execute(sql) sqlRec = cursor.fetchall() close_connection(cursor,con) return sqlRec def insert_update_stmt(sql): con, cursor = connection() cursor.execute(sql) con.commit() close_connection(cursor,con) #if __name__ == '__main__': # function_name_when_single_func(sql) //With a single function I had these uncommented and this worked to run function from another script
from file import *
all the functions in that file should be callable
otherwise you can import specific functions e.g.
from file import function
Answered By – Samantha
Answer Checked By – Timothy Miller (BugsFixing Admin)