i have this function which used to connect to mysql servers the SqlConnector
function is the main function which used to connect to the servers and import the query results the user have two option one is to get the current available locations and second is to get the all locations data while the connection is success and get data until all the lists ip's are connected IterativeOrNotRun
function is used to defined the behavior of the SqlConnector
function if self.IterativeOrNot
True of False the behavior will depend i used the while len(self.IPLists) != 0
to iterate the list until 0 but the code doesn't work.What is wrong with the code?
class MySQLImporter():
def __init__(self,Query,Filename,choices,FileExtension,IterativeOrNot):
self.DataFramesStack = []
self.userdir = os.path.expanduser('~')
self.userdir = self.userdir '\\Documents\\'
self.Filename = self.userdir Filename
self.choices = choices
self.IterativeOrNot = IterativeOrNot
self.LocationDictionary = LocationDict
self.IPLists = AllLocsIPToList(self.LocationDictionary,self.choices)
self.IPLists.reverse()
self.Query = Query
self.FileExtension = FileExtension
self.FailedLocationList = []
FolderCreate(self.Filename)
self.c1_List = []
self.c2_List = []
self.c3_List = []
self.c4_List = []
def CenterListDfAppend(self,df,CenterType):
if CenterType == 'c1':
self.c1_List.append(df)
elif CenterType == 'c2':
self.c2_List.append(df)
elif CenterType == 'c3':
self.c3_List.append(df)
elif CenterType == 'c4':
self.c4_List.append(df)
def AddFailedIp(self,ip):
if ip not in self.FailedLocationList:
self.FailedLocationList.append(ip)
def RmFailedIp(self,ip):
if ip in self.FailedLocationList:
self.FailedLocationList.remove(ip)
def SqlConnector(self):
for ip in reversed(self.IPLists):
CenterAndLocationName = ReturnCenter_Type_Name(ip,self.LocationDictionary)
Center_Type = CenterAndLocationName[0]
Location_Name = CenterAndLocationName[1]
CenterWiseFolderCreate(self.Filename,Center_Type)
try:
cnx = mysql.connector.connect(user=usr,password=passwd,host=ip,database=db,port=3306)
if cnx.is_connected():
print("\nConnection Succesfull {} : {}".format(Location_Name,Center_Type))
print("Remaining Location Count {}".format(len(self.IPLists)-1))
print("Failed Location Count {}\n".format(len(self.FailedLocationList)))
self.RmFailedIp(ip)
LocationCode = cnx.cursor(buffered=True)
LocationCode.execute("select location from syspara")
LocationCode = LocationCode.fetchone()[0]
QueryCursor = cnx.cursor()
QueryCursor.execute(self.Query)
df = pd.DataFrame(QueryCursor.fetchall())
df = df.reset_index(drop=True)
Location_Name_Excel = self.Filename '/' Center_Type '/' LocationCode '.' self.FileExtension
if not df.empty:
self.DataFramesStack.append(df)
self.CenterListDfAppend(df,Center_Type)
Field_Names =[ i[0] for i in QueryCursor.description]
df.columns = Field_Names
ExcelSaver(df,Location_Name_Excel,self.FileExtension)
self.IPLists.remove(ip)
cnx.close()
except mysql.connector.Error as err:
self.AddFailedIp(ip)
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something Wrong With Your Username Or Password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("DATABASE Does Not Exist")
else:
print(err)
if len(self.FailedLocationList)!=0:
self.WriteFailedLocations()
return [self.DataFramesStack,[self.c1,self.c2,self.c3],self.FailedLocationList]
def WriteFailedLocations(self):
self.file = open(self.Filename '/FailedLocations.txt','w')
for ip in self.FailedLocationList:
self.file.write('{}\n'.format(ip))
self.file.close()
def IterativeOrNotRun(self):
if self.IterativeOrNot == True:
while len(self.IPLists) != 0:
return(self.SqlConnector())
elif self.IterativeOrNot == False:
return(self.SqlConnector())
def SaveToExcel(query,filename,choices,fileExtension,iterativeornot):
testobj = MySQLImporter(query,filename,choices,fileExtension,iterativeornot)
queryDatas = testobj.IterativeOrNotRun()
export = dfConcat(queryDatas[0])
Folder = filename '/' filename
FolderCreate(Folder)
ListEmptyOrNot(Folder,fileExtension,filename,export)
print("******** SAVING SUCCESSFULL ********")
QueryToFilesaver(Folder,query)
SaveToExcel(query,'filename',['loctype1','loctype2'],'xls',True)
CodePudding user response:
You have a return inside the while, so when the execution reaches that line it exits immediately. If your goal is that the code resumes at the last point of the list it left last time you need to think in using a generator (and yeild instead of return a connection), but you sure need to rethink your strategy on this.