MySql Database connection with python - mysql

I've got an issue trying to connect to a database with python. It compiles without error but it doesn't seem to do anything. I'm not sure if I'm instantiating the class incorrectly or what the issue may be. Could someone point me in the right direction?
import _mysql
import MySQLdb
class Operations:
def open():
db=_mysql.connect("127.0.0.1","root","admin","test")
c=db.cursor()
#deletes the cursor
def close(self):
c.close()
#verifies the credentials and advances
def login(self):
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
c.execute("""SELECT userid,password FROM members WHERE userid = %s""", (x,))
z = c.password
if y == z:
member_menu()
else:
close()
def new_user(self):
print "Welcome to the Online book store new user registration page!"
print "To begin, please enter your first name: "
fName = raw_input('Please enter your first name: ')
lName = raw_input('Please enter your last name: ')
address = raw_input('Please enter your street address: ')
city = raw_input('Please enter your city: ')
state = raw_input('Please enter your state: ')
zip_code = raw_input('Please enter your zip code: ')
phone = raw_input('Please enter your phone number: ')
email = raw_input('Please enter your email: ')
user_ID = raw_input('Please enter your user id: ')
password = raw_input('Please enter your password: ')
c.executemany("""INSERT INTO members(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,) VALUES (fName, lName, address, city, state, zip_code, phone, email, user_id, password,)""")
print "Your account has been created. returning to the welcome menu. "
welcome()
def welcome(self):
choice = NONE;
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\tWelcome to the Online Book Store\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Member Login\n"
print "2. New Member Registration\n"
print "3. Quit\n"
choice = raw_input('Type in your option: ')
if choice == 1:
login()
elif x == 2:
new_user()
else:
close()
def member_menu(self):
x = NONE
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\t Welcome to the Online Book Store \t\t ***\n"
print "***\t\t\t Member Menu \t\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Search by Author/Title/Subject\n"
print "2. View/Edit Shopping Cart\n"
print "3. Check Order Status\n"
print "4. One Click Check Out\n"
print "5. Logout\n"
print "Type in your option: "
x = raw_input('Please enter your choice. ')
if x == 1:
close_conn(),
elif x == 2:
close_conn(),
elif x == 3:
close_conn(),
elif x == 4:
close_conn(),
else:
close_conn()
def main():
start = Operations()
print "Opening conenction to database"
start.welcome
if __name__ == '__main__':
main()

Well, there are so many problems with your code, that I'll probably miss some of them anyway.
Nothing happens, because your main() function and condition are both parts of the class definition, so all the interpreter sees are actually two imports and a class definition.
Let's say we unindented the main() definition and the condition. All that would happen then is creating an instance of Operations (with no special effects, as you have no custom constructor defined) and printing "Opening connection to database" to the screen, because all the last line in main() does is getting a reference to the welcome() method and ignoring it. You need to call it: start.welcome()
When you do call it, much more problems will appear. NameErrors will probably come first, as you are using identifiers that do not exist in given scopes. It seems you're new to Python's object model and probably coming from a language with a different approach, like C++. In Python all non-static and non-class instance methods take a reference to the object they're operating on as the first parameter, traditionally called 'self'. If you want to access any of the fields of the object, you need to do this through 'self', they are not visible to the interpreter otherwise. E.g.: you open a connection and keep the cursor as c, which you later reuse in other methods:
def open():
# ...
c=db.cursor()
# ...
def login(self):
# ...
c.execute("...")
That's incorrect for two reasons:
your open() method does not take self as a parameter
you're creating c as a local variable in scope of the open() method and then trying to access it in login(), which essentialy results in a "reference before assignment" error.
In order to be correct, it should be written like this:
def open(self):
# ...
self.c = db.cursor()
# ...
def login(self):
# ...
self.c.execute("...")
You're making the same mistake in many places. You need to call self.login(), self.new_user(), self.close(), etc.
You're using Python 2, at least according to the question's tags and there is one thing you need to remember when declaring classes in Python 2. There exist so called old- and new-style classes and what you want to do is use the new-style ones. Therefore your class must inherit from object:
class Operations(object):
# ...
They've finally decided to drop the old-style classes support in Python 3 and there's no need to explicitly inherit from object anymore, but while in Python 2, you need to cope with it.
While there are still some errors or potential errors (what is close_connection()?), I think it's enough for a good start ;). Good luck.

Related

I've stumped myself on my login project and suggestions with the order of my code! it is a login project

So I have the code written I think and it works but I am not sure how to order it properly so for example in my menu function when they enter 2 to end the program it will end completely as after I call this function I need to call the others but at the moment it while just run the next part of the code
print("----------------------Welcome User----------------------\n\n")
# this function is used for apperance in the program
def linebreak():
print("---------------------------------------------------------")
# Menu for user to choose what they would like to do
# this functuon gives the user a choice from the menu above if they want to log in it will break out of
# the loop and go onto the next block of code below
def menu():
while True:
print("-----------------------Main Menu------------------------\n")
print("To login enter 1:")
print("To end the program enter 2:")
print("")
try:
sUserSelection = int(input("What would you like to do? \n"))
# make a conditional statement to see if the user wants to start the login program or exit
if sUserSelection == 1:
break
elif sUserSelection == 2:
print("Ending program, Goodbye!")
break
except:
print("ERROR! Invalid choice please choose from the menu to continue or exit the program.\n")
menu()
menu()
# This is a function that will return two print statements one to tell the user that their login was successful
# And it will then print greet with that users inputted name
def welcome_user():
print("Login successful. ")
print("Welcome ")
# Create a function for the admin login
sAdmin = "admin"
sAdminPassWord = "aDmin002"
def admin_login():
print("Please login to the administrator account to create your new personal account: \n")
while True:
sUserInput = input("Please enter admin username: \n")
sUserInput = sUserInput.lower()
if sUserInput == sAdmin:
break
else:
print("Wrong username please try again! \n")
while True:
sPassInput = input("Please enter admin password: \n")
if sPassInput == sAdminPassWord:
print("Login Successful")
break
else:
print("Wrong password please try again! \n")
# this function allows the user to create a new account starting with the username and then
# it asks for the creation of a password
def new_account():
print("\nPlease create a new account.\n")
while True:
global sNewUser1
sNewUser1 = input("\nPlease enter a new username.\n"
"It should be at least 5 characters long\n"
"and not contain spaces or special characters: \n\n")
if len(sNewUser1) < 5:
print("Your username is too short. Please try again: ")
elif sNewUser1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif sNewUser1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
global sNewPass1
sNewPass1 = input("\n\nPlease enter a new password.\n"
"It should be at least 6 characters long\n"
"with at least one uppercase letter,\n"
"one lowercase letter, one special character"
"and one number: \n\n")
if len(sNewPass1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in sNewPass1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in sNewPass1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in sNewPass1) is False:
print("\nYour password does not contain a number. "
"Please try again: ")
elif any(not char.isalnum() for char in sNewPass1) is False:
print("\nYour password does not contain a special character. "
"Please try again: ")
elif sNewPass1.replace(" ", "") != sNewPass1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
def name_selection():
print("Account created sucessfully!")
global sName1
sName1 = input("Please enter your name:\n")
def user_login():
while True:
sUserLogin = input("Please enter your username:\n")
if sUserLogin == sNewUser1:
break
else:
print("Wrong username please try again:\n")
while True:
sUserPass = input("Please enter your password:\n")
if sUserPass == sNewPass1:
print("\nWelcome: ", sName1)
break
# # calls the menu function
menu()
# # calls the admin login function
admin_login()
# calls the function to create a new account
new_account()
# calls the name creation function after an account has been made
name_selection()
# calls the function to allow the user to login using there credentials
user_login()

World of tanks Python list comparison from json

ok I am trying to create a definition which will read a list of IDS from an external Json file, Which it is doing. Its even putting the data into the database on load of the program, my issue is this. I cant seem to match the list IDs to a comparison. Here is my current code:
def check(account):
global ID_account
import json, httplib
if not hasattr(BigWorld, 'iddata'):
UID_DB = account['databaseID']
UID = ID_account
try:
conn = httplib.HTTPConnection('URL')
conn.request('GET', '/ids.json')
conn.sock.settimeout(2)
resp = conn.getresponse()
qresp = resp.read()
BigWorld.iddata = json.loads(qresp)
LOG_NOTE('[ABRO] Request of URL data successful.')
conn.close()
except:
LOG_NOTE('[ABRO] Http request to URL problem. Loading local data.')
if UID_DB is not None:
list = BigWorld.iddata["ids"]
#print (len(list) - 1)
for n in range(0, (len(list) - 1)):
#print UID_DB
#print list[n]
if UID_DB == list[n]:
#print '[ABRO] userid located:'
#print UID_DB
UID = UID_DB
else:
LOG_NOTE('[ABRO] userid not set.')
if 'databaseID' in account and account['databaseID'] != UID:
print '[ABRO] Account not active in database, game closing...... '
BigWorld.quit()
now my json file looks like this:
{
"ids":[
"1001583757",
"500687699",
"000000000"
]
}
now when I run this with all the commented out prints it seems to execute perfectly fine up till it tries to do the match inside the for loop. Even when the print shows UID_DB and list[n] being the same values, it does not set my variable, it doesn't post any errors, its just simply acting as if there was no match. am I possibly missing a loop break? here is the python log starting with the print of the length of the table print:
INFO: 2
INFO: 1001583757
INFO: 1001583757
INFO: 1001583757
INFO: 500687699
INFO: [ABRO] Account not active, game closing......
as you can see from the log, its never printing the User located print, so it is not matching them. its just continuing with the loop and using the default ID I defined above the definition. Anyone with an idea would definitely help me out as ive been poking and prodding this thing for 3 days now.
the answer to this was found by #VikasNehaOjha it was missing simply a conversion to match types before the match comparison I did this by adding in
list[n] = int(list[n])
that resolved my issue and it finally matched comparisons.

Creating a Caesar Cipher Program in Python 3.4, but function doesn't work

Currently, I am creating a Caesar Cipher but it is not working correctly, can anyone help at all? The code will be below. At the moment, if the program is run first time (as in, no functions have to be re run) it works perfectly, but when the getKey() function is re run, it returns an error. After the code, the error is shown:
def runProgram():
def choice():
userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\nTranslation complete: " + translatedMessage)
runProgram()
I have tried to create it error proof during the getKey() function with the try, except and else commands. It will 'Try' to see that the input is an int or not, if it is, it goes to else, but if it isn't an int, then it will rerun the function. If the function is rerun, and an int is entered, this error is given:
This is an example of it working:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): 5
Translation complete: Mjqqt
This is an example when the getKey() function must be re run due to an int not being entered:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): H
Invalid Option. Please try again.
Enter a key number (1-26): 5
Traceback (most recent call last):
File "C:\Python34\Encryptor2.py", line 54, in
runProgram()
File "C:\Python34\Encryptor2.py", line 52, in runProgram
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
File "C:\Python34\Encryptor2.py", line 35, in getTranslated
num += key
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
As you can see, it re runs the function as I want it too, but the error occurs when adding the key to the ord of character.
The first call to getKey(), with your comment:
key = getKey() #Runs function for user to select key. Saves key choice.
Another place you call it:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
If you were to write that with the same kind of comment, it would be:
getKey() #Runs function for user to select key. Doesn't save key choice.
What the user types in, comes out of getKey() ... and you aren't keeping track of it, so it vanishes. You then do.
return userKey
userKey is still the H you tried to convert to int, the one that failed. You didn't get rid of it, so it's still there.
The better solution is to rework the shape of your code, so getKey() never calls getKey() inside itself. Do the error checking outside, perhaps, like this kind of shape:
def getKey():
prompt user for key
try to convert to int and return the int
if it fails, return None as an indication that getting the key went wrong.
key = None #set some wrong placeholder
while (key is None) or (key < 1) or (key > 26):
key = getKey()
change your input to raw_input
just use the maketrans and translate functions that basically encrypt or decrypt the message for you.they make for a very short and efficient solution to the problem
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
This code really doesn't need to be this complicated at all, if you just use regex the code will be much shorter but (in my opinion) way better.
Here's a code I created for Caesar cipher encrypting, decrypting and using a shift of the user's choice using regex.
import re
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText
selection = input ("encrypt/decrypt ")
if selection == 'encrypt':
plainText = input("What is your plaintext? ")
shift = (int(input("What is your shift? ")))%26
caesar(plainText, shift)
else:
plainText = input("What is your plaintext? ")
shift = ((int(input("What is your shift? ")))%26)*-1
caesar(plainText, shift)

How to obtain a random word using function and dictionary? (Python 3)

The user has to select a category. And from there, the program has to generate a random word from the category list. If the user selected an invalid category, the program will prompt the user to choose a category again (loop the askCat function again).
import random
#Make word dictionary
wordDict = {'Animals':['Giraffe','Dog','Dolphin','Rabbit','Butterfly'], \
'Fruits': ['Apple','Pineapple','Durian','Orange','Rambutan'], \
'Colours': ['Red','Blue','Yellow','Green','Purple'], \
'Shapes': ['Heart','Circle','Rectangle','Square','Diamond']}
#Determine word category and random word
def askCat (wordDict):
category = str( input ("To start the game, please choose a category: \n Animals (a), Fruits (f), Colours (c), Shapes (s) "))
print()
if category == 'a':
print ("You chose the Animals category.")
cat = (wordDict['Animals'])
elif category == 'f':
print ("You chose the Fruits category.")
cat = (wordDict['Animals'])
elif category == 'c':
print ("You chose the Colours category.")
cat = (wordDict['Animals'])
elif category == 's':
print ("You chose the Shapes category.")
cat = (wordDict['Animals'])
else:
print ("You entered an invalid category. Try again!")
print()
askCat(wordDict)
return random.choice(cat)
#Print random word
randWord = askCat(wordDict)
print (randWord)
When on the first try, the user enter a valid category, the program works just fine. However, the problem I'm facing is that, when the user enter an invalid category the first time, and when he enter a valid category the second time, the program don't work anymore.
Please do help! Thanks (:
else:
print ("You entered an invalid category. Try again!")
print()
askCat(wordDict)
return random.choice(cat)
In the else branch, you are recursively calling the function again—which is okay—and then you discard its return value and return cat instead which, in this call of the function, was never set.
Instead, you should return the value from the recursive call:
else:
print ("You entered an invalid category. Try again!")
print()
return askCat(wordDict)
return random.choice(cat)
That way, when you call it recursively, the result from that call will be used, and not the one you tried to get from the current cat.
Furthermore, in each of your branches, you are doing cat = (wordDict['Animals']); you probably want to change that so you actually get fruits for f etc.
And finally, while using recursion is okay, it’s not the best way to handle this. Recursion always has a maximum depth it can into, so in the worst case, a user could keep answering the wrong thing increasing the recursion stack further, until the program errors out. If you want to avoid that, you should use a standard loop instead:
cat = None
while not cat:
# You don’t nee to use `str()` here; input always returns a string
category = input("To start the game, please choose a category: \n Animals (a), Fruits (f), Colours (c), Shapes (s) ")
print()
if category == 'a':
print("You chose the Animals category.")
cat = wordDict['Animals'] # no need to use parentheses here
elif category == 'f':
# ...
# and so on
else:
print("You entered an invalid category. Try again!")
# the loop will automatically repeat, as `cat` wasn’t set
# when we reach here, `cat` has been set
return random.choice(cat)
In your function askCat, if the user first enter a wrong category, you call again askCat. However, you don't return the value returned by that call.
Replace (in the function askCat):
askCat(wordDict)
to:
return askCat(wordDict)
However, I would strongly recommend you to use a while loop instead.

python-mysql fetchone() type mismatch?

I have this piece of code that should return the value of the password from the db and match it with the password entered. I appended the characters on this line to match the formatting of the result that it printed.
appended_y= "(u'" + y + "'y,)"
it even though the two print out the same value the if statement rejects it and always falls to else, Can anyone point me down the right path?
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
appended_y= "(u'" + y + "'y,)"
z = "SELECT password FROM members WHERE userid = %s"
self.cursor.execute(z,(x,))
pw=(self.cursor.fetchone())
if appended_y == pw:
self.member_menu()
else:
print "Incorrect name or password. Aborting connection"
Look into the type of pw. It may be a string inside a list or tuple.