Python MYSql.connector will not insert data - python

I am trying to insert some data into a a database I am making and it will not insert. I literally have used the same insert method on other code and it still seems to work, however this one refuses to. Help!
from Bio import Entrez
from sys import exit
Entrez.email = "A.N.Other#example.com" # Always tell NCBI who you are
sranumber = raw_input("Input SRA number here")
sranumber2= raw_input("re-type SRA number here")
while True:
if sranumber != sranumber2:
print "SRA numbers do not match"
sranumber2 = raw_input("Please re-type sra number to match intitial sra number")
continue
else:
break
print "SRA ID:" + sranumber
#answer = raw_input("Are you sure this is the sra number you wish to use? Type Y/N")
while True:
answer = raw_input("Are you sure this is the sra number you wish to use? Type Y/N")
if answer == "Y":
print "Let's do it!"
break
elif answer == "y":
print "Let's do it!"
break
elif answer == "yes":
print "Let's do it!"
break
elif answer == "YES":
print "Let's do it!"
break
elif answer == "N":
exit()
else:
print "Not a valid answer"
search = Entrez.esearch(term = sranumber, db = "SRA", retmode = "xml")
record = Entrez.read(search, validate = False)
newstuff = record
#print newstuff
for j in record:
if j == "WarningList":
newstuff = record['WarningList']
#print newstuff
poop = newstuff
for item in poop:
if item == "OutputMessage":
poop = poop['OutputMessage']
#print poop
crap = ['Wrong UID' + " " + sranumber]
cool = "'"+crap[0]+"'"
#print cool
continuity = ''
for j in poop:
if j == 'No items found.' or j == cool:
print "[-] This is not a valid SRA identity"
continuity = 'done'
if continuity == 'done':
exit()
print "[+] This is a valid SRA identity"
print "SRA ID:" + sranumber
condition = raw_input("Type in the condition of your ngs_data here")
condition2 = raw_input("re-type the condition of your ngs_data here")
print condition
while True:
if condition != condition2:
print "Conditions do not match!"
condition2 = raw_input("Please retype condition here to match first condition")
else:
break
print "just dropped in to check on what condition my condition was in"
stuff = []
stuff.append(sranumber)
stuff.append(condition)
stuff2 = '+'.join(stuff)
print stuff2
stuff3 = stuff2.split('+')
print stuff3
experiment = [tuple(stuff3)]
print experiment
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def insert_books(experiment):
query = "INSERT IGNORE INTO organisms(sra#, condition) " \
"VALUES(%s,%s)"
try:
db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()
cursor.executemany(query, experiment)
conn.commit()
except Error as e:
print('Error:', e)
finally:
cursor.close()
conn.close()
def main():
insert_books(experiment)
if __name__ == '__main__':
main()

I ended up just doing it this way and it finally worked. I am unsure why it did not work before but I believe that it had something to do with the formatting of how i typed in the columns.
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
cnx = mysql.connector.connect(user='root',password='*****',database = 'new')
cursor = cnx.cursor()
addstuff= ("INSERT IGNORE INTO experiment (`sra`, `condition`) VALUES(%s,%s)")
cursor.execute(addstuff,stuff3)
cnx.commit()
cursor.close()
cnx.close()

Related

If there is no answer I want it to pass Python

If there is no answer I want it to pass. I don't want it to write in an excel table. If there is no answer, I want you to move on to the next question.
I'm sorry I don't know much English. If there is an answer, do not write anything in the excel table. skip to the next question
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt","r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv","a",encoding="utf_8")
try:
query = query.replace("\n","")
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0,query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
try:
answer = str(paa.get_answer(i)['response'])
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")
If you want to detect that the input is blank, then just add a condition in your code.
inputvar = input("Enter string: ")
if inputvar == "":
print("Blank input entered!")
else:
print(inputvar)
But just whatever you do, do not enter a .replace("", "None") code in your project because this can cause a serious error: Even if you enter an answer the input variable, it will enter None after each letter/symbol you enter!
Code:
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt", "r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv", "a", encoding="utf_8")
try:
if query == "":
query = query.replace("\n", "")
else:
pass
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0, query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
answer = str(paa.get_answer(i)['response'])
try:
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")

Im getting an error but my code is working. Python and PostgreSQL

I am getting not all arguments converted during string formatting, but my code is actually working. Can someone tell me what is wrong with my code?
When I run this, it returns the error, but whenI look at the list wo workes by calling Query_Workers(), it appears that the person I chose had been removed successfully.
def Remove_Directors(id, name):
conn = None
try:
# read the connection parameters
params = config()
# connect to the PostgreSQL server
conn = psycopg2.connect(**params)
cur = conn.cursor()
# create table one by one
#for command in commands:
# cur.execute(command)
SQL = "DELETE FROM directors WHERE id = (%s);"
#cur.execute("DELETE FROM directors WHERE id = (%s)", (id))
id = (id, )
cur.execute(SQL, id)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
print ("%s has been removed from Directors.") % (name)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
def Modify():
print "Choose Options"
option = raw_input("Press A for adding a member, R for removing a member, or V for Viewing members: ")
if option.upper() == "A":
print "Adding a member."
Director_or_EventManager = raw_input("Is the new member a director or an event manager?\nPress D for Director or E for Event Manager:")
if Director_or_EventManager.upper() == "D":
ID_Entered_Correctly = False
while ID_Entered_Correctly == False:
id = raw_input("Enter 10 digit ID: ")
if len(id) == 10:
ID_Entered_Correctly = True
else:
print "Invalid ID"
name = raw_input("Enter Name: ")
Add_Directors(id, name)
if Director_or_EventManager.upper() == "E":
ID_Entered_Correctly = False
while ID_Entered_Correctly == False:
id = raw_input("Enter 10 digit ID: ")
if len(id) == 10:
ID_Entered_Correctly = True
else:
print "Invalid ID"
name = raw_input("Enter Name: ")
Add_Event_Managerss(id, name)
elif option.upper() == "R":
print "Removing a member."
Director_or_EventManager = raw_input("Is the member a director or an event manager?\nPress D for Director or E for Event Manager:")
if Director_or_EventManager.upper() == "D":
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute("SELECT id, name FROM directors ORDER BY name")
directors = cur.fetchall()
print ("\tNumber\tID\t\tName")
ids = []
names = []
count = 1
for director in directors:
print ("\t%s\t%s\t%s") % (count, director[0], director[1])
ids.append(director[0])
names.append(directors[1])
count += 1
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
count -= 1
num_director = int(raw_input("Enter the number of director to remove: "))
if num_director <= 0 or num_director > count:
print "Invalid entry"
else:
id = ids[num_director - 1]
name = names[ids.index(id)]
print id
print name
Remove_Directors(id, name)
elif option.upper() == "V":
Query_Workers()
else:
print "Invalid option"
The error seems to occur after the query, so it doesn't impact the data change, only the output debugging.
You just need to change those lines :
print ("%s has been removed from Directors.") % (name)
to
print ("%s has been removed from Directors." % name)
and also :
print ("\t%s\t%s\t%s") % (count, director[0], director[1])
to
print ("\t%s\t%s\t%s" % (count, director[0], director[1]))

Optimize python code with return in the code

I want to optimize my code to return well in a part of a code.
I know that I can do that with do while but I think it's maybe heavy with a lot of do while.
I identify where I want to return in comments
Can you suggest me a solution to solve my problem?
#return here 0
mainMenu()
choix = input()
if choix == 1:
print "Enter your username"
username = raw_input()
print "Enter your password"
password = raw_input()
createAccount.createAccount(username,password)
#return here 1
educatorMenu()
choix = input()
if choix == 1:
print "Enter his age"
ageChild = raw_input()
print "Enter his photo"
photoChild = raw_input()
educator.createChildAccount(ageChild, photoChild)
elif choix == 2:
childrenList = educator.seeChildrenList()
#Return to where it is written "return here 0"
elif choix == 3:
childrenList = educator.seeChildrenList()
print "Associate children?"
choixEnfant = input()
educator.associateChildren(childrenList,choixEnfant-1, educator.getIdEducator(username))
#Return to where it is written "return here 1"
Thanks a lot.
Note: I will not re-write/optimize your code, because I feel it should be a task for you to do so. Furthermore, there are quite some functions and references missing to rewrite it; you did not deliver an MWE.
Consequently, you may find this useful as a starting point and try to adapt this (very basic structure) to suit your needs. However, be warned: This also is far from being efficient, but it will help you to extend your knowledge of the basics.
def menu_main():
q = ['What would you like to do?',
'1: List educators',
'2: Create educator',
'3: Manage educator\'s children',
'4: Exit'].join('\n ')
return int(input(q).strip()[0])
def menu_educator_create():
usr = input('Enter username:').strip()
pwd = input('Enter password:').strip()
return (usr, pwd)
def menu_educator_manage():
q = ['What would you like to do?',
'1: List children',
'2: Add child',
'3: Return'].join('\n ')
return int(input(q).strip()[0])
if __name__ == '__main__':
edus = {}
exit = False
while not exit:
print('===')
cmd = menu_main()
if cmd == 1:
# List educators
pass
elif cmd == 2:
# Create educator
usr, pwd = menu_educator_create()
pass
elif cmd == 3:
# Manage children
# (should somehow obtain current educator first)
exit_edu = False
while not exit_edu:
subcmd = menu_educator_manage()
if subcmd == 1:
# List children
pass
elif subcmd == 2:
# Add child
pass
elif subcmd == 3:
# Return
exit_edu = True
else:
# None of the above
print('Unknown choice from educator menu.')
elif cmd == 4:
# Exit
exit = True
else:
# None of the above
print('Unknown choice from main menu.')

Menu prompt doesn't work

I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).

update and save data to a .txt file daily

I'm trying to create something similar to a journal of my daily fluid intake, food, exercise, etc. I have created a few menus do ask user for specific input that is pre-defined in the menus. From there I need to collect all the output print data and save to a file, the file will be updated daily (asking the user for the same pre-defined input.
Code is pretty long, but looks like this:
health = open('healthy.txt','a+')
date = input('Date: ')
#Loop Menu for Exercise info for that day.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Yoga")
print ("2 = Cardio")
print ("3 = Walk")
print ("4 = Dance")
print ("5 = Rest/None")
print ("D = Done")
print ("----------------------------------")
print ()
exer = input('Exercise: ')
if (exer =='1'):
print("Yoga")
elif (exer =='2'):
print("Cardio")
elif (exer =='3'):
print ("Walk")
elif (exer =='4'):
print ("Dance")
elif (exer == '5'):
print ("Rest/None")
elif (exer =='d' or exer =='D'):
loop=False
else:
print ("Invalid Option")
#End Exercise Menu
dur = input('Duration(in minutes): ')
#Loop menu for the Food Intake for particular date.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Protein")
print ("2 = Starch")
print ("3 = Fruit")
print ("4 = Vegetable")
print ("D = Done")
print ("----------------------------------")
print ()
food = input('Food: ')
if (food =='1'):
print("Protein")
elif (food =='2'):
print("Starch")
elif (food =='3'):
print ("Fruit")
elif (food =='4'):
print ("Vegetable")
elif (food =='d' or food =='D'):
loop=False
else:
print ("Invalid Option")
#End Food Menu
fluid = input('Fluid Intake Total: ')
#for line in health:
#Final print of info to be written to file
#not sure if I need the next four lines
food_true = False
food_total = 0
exer_true = False
exer_total = 0
for char in exer:
if (exer_true == "Yoga"):
print ("Yoga", end=" ")
if (exer_true == "Cardio"):
print ("Cardio", end=" ")
if (exer_true == "Walk"):
print ("Walk", end= " ")
if (exer_true == "Dance"):
print ("Dance",end=" ")
if (exer_true == "Rest/None"):
print ("Rest/None",end=" ")
else:
loop=False
while(loop):
if (food_true == "Protein"):
print ("Protein", end=" ")
if (food_true == "Starch"):
print ("Starch", end=" ")
if (food_true == "Fruit"):
print ("Fruit", end= " ")
if (food_true == "Vegetable"):
print ("Vegetable",end=" ")
else:
loop=False
print ("{:>10}".format("Date: "),date)
print ("{:>10}".format("Exercises: "),exer_total)
print ("{:>10}".format("Duration: "),dur)
print ("{:>10}".format("Foods: "),food_total)
print ("{:>10}".format("Fluids: "),fluid)
print("-"*60)
#Save/Write to file function will be here
#Save/Write to file function will be here
health.write(info)#word "info" is a place holder only for final code info
health.close()
I want to be able to print out the info only (this does not include saving the info to the file)for the following in a neat looking file(format doesn't really matter as long as it is neat): Date: output; Exercise: output(all if applicable) ;Duration:output ;Food:output(all four if applicable);Fluids: output
Each day I will run the program and update my daily info for all the above.
Then the file needs to have the info written and saved to the same file each day(cannot be a new file each day, hence the use of the the following at start of the code, this is a MUST):
health = open('healthy.txt','a+')

Categories

Resources