Comparing user input to usernames in database - mysql

I am having an issue with comparing user input to a database of already used usernames. The database is working exactly how it is supposed to, but what seems like a simple task it proving to be more difficult than I thought. I figure I am missing something really simple! I get no error codes from the code but it does not print "username is taken" when the username is in fact in the database.
Thus far I have tried a for loop to compare the user's input to the database, I have tried making a list of the usernames in the database and iterating through the list to compare the user input:
### check to see if the user is already in the database
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
searchdb = 'SELECT username FROM userpass'
mycursor = mydb.cursor()
mycursor.execute(searchdb)
username = mycursor.fetchall()
print(username)
user = input('username')
for i in username:
if user == username:
print('username is taken')
else:
print("did not work")
Output that does not work:
[('Nate',), ('test',), ('test1',), ('test2',), ('n',), ('test4',)] username: n
('Nate',)
('test',)
('test1',)
('test2',)
('n',)
('test4',)
I expect the above code to iterate through each database entry and compare it to the user's input to verify that the username is not already taken. It should print "username is taken" instead it prints "did not work".

Welcome to Stack Overflow Nate!
You can use:
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()
To create a variable called 'results' that stores all (*) of the column values for the record in the userpass database table where the username of the record is equal to the value of the user variable.
You can then use an if statement:
if results:
That is run if the results variable has a value (if there is a record with a username that is equal to the value of the user variable in the table) AKA if the username is taken.
This if statement can then, when run print 'username is taken'
The full code:
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
user = input('username')
mycursor.execute("SELECT * FROM userpass WHERE username = ?", [(user)])
results = cursor.fetchall()
if results:
print('username is taken')
else:
print("did not work")

edit* when adding this code the the rest of the program and testing i found it gives the results username taken every time, even if it is a new username. If you have any recommendations to fix this, I am open to them. I am going to continue work on this and will post results when the program is working properly.
I would like to thank you guys for your help, I did find the response I was looking for!
### check to see if user is already in database
import mysql.connector
# Database entry
mydb = mysql.connector.connect(
host='Localhost',
port='3306',
user='root',
passwd='passwd',#changed for help
database='pylogin'
)
mycursor = mydb.cursor()
user = input('username')
mycursor.execute('SELECT * FROM userpass WHERE username = username')
results = mycursor.fetchall()
if results:
print('Username is taken')
else:
print('did not work')`

Related

How to give a mysql record a timeout to expire after 30 minutes?

I was not able to find something relevant anywhere.
I would like to put a timeout on "password" that I am saving on mysql with python.
cur.execute("INSERT INTO generatedcode(password, codetimeout) VALUES (%s,
%s)", [passwordd, timestamp])
As I'm not sufficiently acquainted with python and hence I'll leave the specifics of the code to you; I will only present the idea of the solution and the relevant SQL commands (syntax will need to be verified as I don't have an environment to test it).
Let say that you want to set a timeout of 1 hour from the moment you save the password and your table has (at least) the following two fields: Password and Expiration (I assume that Password would be of binary type to allow encryption and Expiration would be of DATETIME type).
Then, you would implement the following SQL command:
INSERT INTO <your table> (Password , Expiration )
VALUES (%s , DATEADD(NOW(),3600))
[spaces added just for clarity purposes]
and send that string towards the DB where %s would be replaced by the value of the password.
What DATEADD(NOW(),3600) does is:
Gets the current date and time,
Adds one hour to it.
Once you have that inserted into your table, you would later on retrieve the password using the following command:
SELECT Password
FROM <your table>
WHERE User = <could be Username or any other key that you are using now>
AND Expiration > NOW()
meaning, get the password (if any) that its expiration datetime is still in the future.
Hope this is what you were looking for.
Cheers!!
EDIT:
I'm adding hereinafter your code after fixes:
#app.route('/signattendance', methods=['GET'])
def signattendance():
stamp = "signed"
error = None
# now = datetime.datetime.today()
# tdelta = datetime.timedelta(seconds=10000)
now = datetime.datetime.now()
if request.method == 'GET':
cur1 = mysql.connection.cursor()
result = cur1.execute("SELECT password FROM generatedcode WHERE codetimeout > NOW()")
if result is False:
cur = mysql.connection.cursor()
cur.execute("INSERT INTO attendance(studentattendance) VALUES(%s,DATEADD(NOW(),3600)", [stamp])
mysql.connection.commit()
cur.close()
# cur1.close()
flash('Succsefully signed', 'Acepted')
else:
flash('You couldnt sign attendance', 'Denied')
else:
return redirect(url_for('dashboard'))
return render_template('signattendance.html', error=error)
Note that I leave for the DB to check the current time.
if request.method == 'GET' or 'POST':
cur1 = mysql.connection.cursor()
result = cur1.execute("SELECT password FROM generatedcode "
"WHERE DATE_SUB(CURRENT_TIME (),INTERVAL 10 MINUTE) <= codetimeout;")

Values are not inserted into MySQL table using pool.apply_async in python2.7

I am trying to run the following code to populate a table in parallel for a certain application. First the following function is defined which is supposed to connect to my db and execute the sql command with the values given (to insert into table).
def dbWriter(sql, rows) :
# load cnf file
MYSQL_CNF = os.path.abspath('.') + '/mysql.cnf'
conn = MySQLdb.connect(db='dedupe',
charset='utf8',
read_default_file = MYSQL_CNF)
cursor = conn.cursor()
cursor.executemany(sql, rows)
conn.commit()
cursor.close()
conn.close()
And then there is this piece:
pool = dedupe.backport.Pool(processes=2)
done = False
while not done :
chunks = (list(itertools.islice(b_data, step)) for step in
[step_size]*100)
results = []
for chunk in chunks :
print len(chunk)
results.append(pool.apply_async(dbWriter,
("INSERT INTO blocking_map VALUES (%s, %s)",
chunk)))
for r in results :
r.wait()
if len(chunk) < step_size :
done = True
pool.close()
Everything works and there are no errors. But at the end, my table is empty, meaning somehow the insertions were not successful. I have tried so many things to fix this (including adding column names for insertion) after many google searches and have not been successful. Any suggestions would be appreciated. (running code in python2.7, gcloud (ubuntu). note that indents may be a bit messed up after pasting here)
Please also note that "chunk" follows exactly the required data format.
Note. This is part of this example
Please note that the only thing I am changing in the above example (linked) is that I am separating the steps for creation of and inserting into the tables since I am running my code on gcloud platform and it enforces GTID standards.
Solution was changing dbwriter function to:
conn = MySQLdb.connect(host = # host ip,
user = # username,
passwd = # password,
db = 'dedupe')
cursor = conn.cursor()
cursor.executemany(sql, rows)
cursor.close()
conn.commit()
conn.close()

odoo 9 migrate binary field db to filestore

Odoo 9 custom module binary field attachment=True parameter added later after that new record will be stored in filesystem storage.
Binary Fields some old records attachment = True not used, so old record entry not created in ir.attachment table and filesystem not saved.
I would like to know how to migrate old records binary field value store in filesystem storage?. How to create/insert records in ir_attachment row based on old records binary field value? Is any script available?
You have to include the postgre bin path in pg_path in your configuration file. This will restore the file store that contains the binary fields
pg_path = D:\fx\upsynth_Postgres\bin
I'm sure that you no longer need a solution to this as you asked 18 months ago, but I have just had the same issue (many gigabytes of binary data in the database) and this question came up on Google so I thought I would share my solution.
When you set attachment=True the binary column will remain in the database, but the system will look in the filestore instead for the data. This left me unable to access the data from the Odoo API so I needed to retrieve the binary data from the database directly, then re-write the binary data to the record using Odoo and then finally drop the column and vacuum the table.
Here is my script, which is inspired by this solution for migrating attachments, but this solution will work for any field in any model and reads the binary data from the database rather than from the Odoo API.
import xmlrpclib
import psycopg2
username = 'your_odoo_username'
pwd = 'your_odoo_password'
url = 'http://ip-address:8069'
dbname = 'database-name'
model = 'model.name'
field = 'field_name'
dbuser = 'postgres_user'
dbpwd = 'postgres_password'
dbhost = 'postgres_host'
conn = psycopg2.connect(database=dbname, user=dbuser, password=dbpwd, host=dbhost, port='5432')
cr = conn.cursor()
# Get the uid
sock_common = xmlrpclib.ServerProxy ('%s/xmlrpc/common' % url)
uid = sock_common.login(dbname, username, pwd)
sock = xmlrpclib.ServerProxy('%s/xmlrpc/object' % url)
def migrate_attachment(res_id):
# 1. get data
cr.execute("SELECT %s from %s where id=%s" % (field, model.replace('.', '_'), res_id))
data = cr.fetchall()[0][0]
# Re-Write attachment
if data:
data = str(data)
sock.execute(dbname, uid, pwd, model, 'write', [res_id], {field: str(data)})
return True
else:
return False
# SELECT attachments:
records = sock.execute(dbname, uid, pwd, model, 'search', [])
cnt = len(records)
print cnt
i = 0
for res_id in records:
att = sock.execute(dbname, uid, pwd, model, 'read', res_id, [field])
status = migrate_attachment(res_id)
print 'Migrated ID %s (attachment %s of %s) [Contained data: %s]' % (res_id, i, cnt, status)
i += 1
cr.close()
print "done ..."
Afterwards, drop the column and vacuum the table in psql.

python mysql (fetch whole table)

i am new to python and mysql,
i have to present a code to my office head. this code should help pull a table called "customer". I just want assistance to know if there are any errors in my code.
hostname = 'localhost'
port =
username = 'USERNAME'
password = 'PASSWORD'
database = 'DBNAME'
# Open database connection
conn = pymysql.connect(host=hostname, port=,user=username, passwd=password, db=database)
cur = conn.cursor()
cur.execute("SELECT * customer")
print(cur)
db.close()
Thanks in Advance,
Ninad.
I am using python 3.6
You may need to print
cur.fetchall()
to have your results appear

Python 2.7 trying to iterate file with usernames and passwords, unable to get data properly

I am using Python 2.7 and I have a text file exactly in this format starting like this:
Username: JohnDoe
Password: JohnsPass
------------------------
Username: Bob
Password: BobsPass
------------------------
It starts the same way you see above and ends the same way as you see.
I have tried the following to get the data in either a dictionary/list so I can import it into mysql.
thefile = open("theaccounts.txt","r")
myAcctList=[]
for line in thefile:
myAcctList.append(line)
thefile.close()
Which shows me:
['Username: JohnDoe\n',
'Password: JohnsPass\n',
'------------------------\n',
'Username: Bob\n',
'Password: BobsPass\n',
'------------------------\n']
I have been trying to get the username/password like so:
for userinfo in myAcctList:
if userinfo.startswith('-------------'):
pass
else:
print userinfo
It shows me:
Username: JohnDoe
Password: JohnsPass
Username: Bob
Password: BobsPass
How can I get this to be on one line or a dictionary even so I can import these into mysql DB? I have tried various things but, they all either error out or it doubles the print out showing the username twice and the password from the previous username as the password.
Is there some way I can do:
print "Username is: %s and password is: %s" % (usernameis,passwordis)
As I would like to set the variable to place into the mysql record in one go, instead of matching the username and then inserting the password.
Please provide suggestions or solutions I have been trying to figure this out and really haven't been able to get it right. Thanks for all input it is greatly appreciated!
Update:
I modified what you showed me and came up with this:
cur_user={}
countlogins=0
for userinfo in myAcctList:
if userinfo.startswith('------------------------'):
pass
else:
forusername=userinfo.split(':')
print "I see index 0 as: %s" % forusername[0]
print "I see index 1 as: %s" % forusername[1]
cur_user[forusername[0]] = forusername[1].strip()
print cur_user
time.sleep(3) #just so I could see the top of the list
This is closer but, it still does some weird doubling up showing the username twice and showing the password for the previous line then the password it should be. It also only shows me the username when it hits the first line (I am guessing because it has not iterated to the 2nd line yet).
Print out is like so:
I see index 0 as: Username
I see index 1 as: JohnDoe
{'Username': 'JohnDoe'}
I see index 0 as: Password
I see index 1 as: JohnPass
{'Username': 'JohnDoe', 'Password': 'JohnPass'}
I see index 0 as: Username
I see index 1 as: BobTheUser
{'Username': 'BobTheUser', 'Password': 'JohnPass'}
I see index 0 as: Password
I see index 1 as: BobsPass
{'Username': 'BobTheUser', 'Password': 'BobsPass'}
I see index 0 as: Username
I see index 1 as: ThisOtherUser
{'Username': 'ThisOtherUser', 'Password': 'BobsPass'}
I counted 5 logins
I see index 0 as: Password
I see index 1 as: ThisOtherUserPass
{'Username': 'ThisOtherUser', 'Password': 'ThisOtherUserPass'}
I see index 0 as: Username
I see index 1 as: YetOneMore
I cannot figure out why it's doubling up like that or why it takes it the 2nd go round to get the info right. This will prevent (if I'm not mistaken) proper insertion into mysql db. I would like to get it just telling me once what I need to know so that I can know it will insert the proper info.
Thanks for your time and assistance!
2nd Update:
I also tried:
theFile = open("theaccounts.txt","r")
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = ':'.split(line)
cur_user[fields[0]] = fields[1].strip()
theFile.close()
Which gives me an error:
---> 10 cur_user[fields[0]] = fields[1].strip()
11 theFile.close()
IndexError: list index out of range
So I then tried:
theFile = open("theaccounts.txt","r")
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = ':'.split(line)
try:
cur_user[fields[0]] = fields[1].strip()
print cur_user
except:
pass
theFile.close()
Which only gave me:
[{},
{},
{},
{},
{},
{},
{},
{}]
Please help me get this sorted it's really not making sense to me why it's so hard.
3rd Update:
Ok got it figured out! Here is the final result for anyone else who might be needing to do this or gets in trouble:
countlogins=0
theFile = open("theaccounts.txt","r")
myAcctList=[]
cur_user={}
for line in theFile:
if line.startswith('------'):
countlogins=countlogins+1
print cur_user
myAcctList.append(line)
cur_user={}
else:
forusername=line.split(':')
cur_user[forusername[0]] = forusername[1].strip()
theFile.close()
print "I counted %s logins" % countlogins
I did the extra count at the end to verify it matched with what I was told.
Thanks for your help!
Split the line using : as the delimiter. Then use the first part as the key in a dictionary, and the second part as the value. When you get to the ---- line, add the dictionary to your list.
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = line.split(':')
cur_user[fields[0]] = fields[1].strip()
In your first update, the doubling up is happening because you're using the same cur_user dictionary for everything. So when you read the second username, you're just overwriting the username of that dictionary, not starting a new one. That's why my answer reassigns cur_user = {} after it adds the current user to the users list.
It takes two steps to get both the username and password into the dictionary, because when you read the first line of the file you haven't yet read the first password. Since you're printing the dictionary after each line, you see this partial result after the first line. You shouldn't try to add to the database until you get to the ----- separator line, that's how you know you have both fields.