I have a database in mysql, and I'm working in a app in QT4, I'm using Mysqldb connector, I'm already successfully connected to the database, but when I'm querying the table t_usuarios I don't know how to eval it. Can you help me? Thanks in advance.
Part of my code:
def chequeouser(self):
passwdcheck = str(txt_password.text())
usuariover = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariover, passwdcheck))
checar = cursor.fetchone()
Thanks for the user who answer me ... I do it, but with some modification as follow ..
passwdcheck = str(txt_password.text())
usuariocheck = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariocheck, passwdcheck))
row = cursor.fetchone()
if row == None:
print "no data:"+ usuariocheck
return
if row[1] == passwdcheck:
print "user and password combination is correct" +usuariocheck
else :
print "your input is incorrect"
I'm thinking do this in answer but I not sure if this is correct or not.
fetchone() returns a row of data. The first item is row[0], 2nd item is row[1], etc.
Example:
def chequeouser(self):
passwdcheck = str(txt_password.text())
usuariover = str(txt_usuario.text())
# datosLogin = "SELECT * FROM t_usuarios WHERE id_usuario = 'usuario' AND pasword = 'password'
cursor = dbase.cursor()
cursor.execute("SELECT id_usuario, password FROM t_usuarios WHERE id_usuario = %s AND password = %s", (usuariover, passwdcheck))
row = cursor.fetchone()
if not row:
print "no rows!"
return
if passwdcheck == row[1]:
print 'MATCH for user', row[0]
else:
print 'uhoh'
Related
import sqlite3
import traceback
from time import sleep
import mysql.connector
def check_user(user_id):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS online(id INT, last_online_date TEXT)')
conn.commit()
select = "SELECT * FROM online WHERE id = %s LIMIT 0, 1"
result = cur.execute(select, (user_id,))
if result is None:
insert = ('INSERT INTO online (id, last_online_date) VALUES (%s, %s)')
cur.reset()
cur.execute(insert, (user_id, online_time))
conn.commit()
def update_online_status(user_id, online_time):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cursor = conn.cursor()
select = 'SELECT last_online_date FROM online WHERE id = %s'
result = cursor.execute(select, (user_id,))
old_online = result
online_time = f'{old_online},{online_time}'
cursor.reset()
cursor.execute('UPDATE online SET last_online_date = %s WHERE id = %s', (online_time, user_id))
conn.commit()
app = Client("my_account")
app.start()
while True:
try:
with open('ids.ini', 'r') as file:
users = file.read().splitlines()
for user in users:
result = app.get_users(user)
user_id = result['id']
if result['status'] == 'offline':
unix_timestamp = float(result['last_online_date'])
local_timezone = tzlocal.get_localzone()
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
online_time = local_time.strftime("%Y/%m/%d %H:%M:%S")
elif result['status'] == 'online':
now = datetime.now()
online_time = now.strftime("%Y/%m/%d %H:%M:%S")
check_user(user_id)
update_online_status(user_id, online_time)
# sleep(300)
except Exception:
traceback.print_exc()
continue
app.stop()
I am writing a program that would read the online status of a user in telegram.
Instead of writing online to an existing user, a huge number of identical rows appear in the database.
Example:
Table with repetitions
When I try to fix something, there are a lot of errors.
mysql.connector.errors.programmingerror: not all parameters were used in the sql statement
mysql.connector.errors.internalerror: unread result found
and other...
Pls help!!
Why my check_email error, i dont know how to fix it
def getLoginDetails():
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
if 'email' not in session:
loggedIn = False
firstName = ''
noOfItems = 0
else:
loggedIn = True
cur.execute("SELECT userId, firstName FROM users WHERE email = '" + session['email'] + "'")
userId, firstName = cur.fetchone()
if 'email' == "admin#shop.com":
check_email = True
else:
check_email = False
cur.execute("SELECT count(productId) FROM kart WHERE userId = " + str(userId))
noOfItems = cur.fetchone()[0]
conn.close()
return (loggedIn, firstName, noOfItems, check_email)
#app.route("/")
def root():
loggedIn, firstName, noOfItems, check_email = getLoginDetails()
with sqlite3.connect('database.db') as conn:
cur = conn.cursor()
cur.execute('SELECT productId, name, price, description, image, stock FROM products')
itemData = cur.fetchall()
cur.execute('SELECT categoryId, name FROM categories')
categoryData = cur.fetchall()
itemData = parse(itemData)
return render_template('home.html', itemData=itemData, loggedIn=loggedIn, firstName=firstName, noOfItems=noOfItems, categoryData=categoryData, check_email=check_email)
This makes no sense to me as I clearly initialize check_email as one of the first lines of my code, and I even labeled it as global just to be safe and make sure it was within the scope of all my methods.
Error: UnboundLocalError: local variable 'check_email' referenced before assignment
You don't assign to check_email if 'email' not in session.
Username is a variable that is drawn from an Entrybox using tkinter. I need for dbsalt to return the outcome of the cursor1.execute query as a string, but it returns "none" or presents a traceback that states "NoneType has no attribute getitem". I do not understand what is incorrect.
def login_verification(self):
sql = ("SELECT salt FROM User WHERE username = %s")
username = self.KUEntry.get()
print username
cursor1.execute(sql, username)
dbsalt = cursor1.fetchone() [0]
print dbsalt
sql2 = ("SELECT PashHash FROM User WHERE username = %s")
cursor2.execute(sql2, username)
dbhash = cursor2.fetchone() [0]
print dbhash
test = hashlib.sha512(username + dbsalt).hexdigest()
print test
if test == dbhash:
self.intro_screen
else:
print "incorrect password"
You didn't call execute method, but assigned to it. Call it using cursor.execute(..):
And you should use ' to quote the string.
username = self.KUEntry.get()
cursor1.execute("SELECT salt FROM User WHERE username = '%s'" % username)
dbsalt = str(cursor1.fetchone())
print dbsalt
BTW, it is better to use parameter passing style than manually formatting string to prevent SQL injection.
cursor1.execute("SELECT salt FROM User WHERE username = %s", [username])
Getting single row and single column below code is executed sucessfully. How to get multiple columns and rows?
views.py
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body></html>" % email_address
else:
row = cursor.fetchone()
html = "<html><body>E-Mail address %s.</body></html>" % row[0]
return HttpResponse(html)
Please help me with this.
UPD:
def get_db_data(request):
conn = MySQLdb.connect (host = "localhost", user = "test_user", passwd = "test_pwd", db = "myproject")
cursor = conn.cursor ()
cursor.execute ("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id %s.</body> <html>" % email_address
else:
html = "<html>"
for x in cursor.fetchone():
html += "<body>E-Mail address %s.</body>" % x
html += "<html>"
return HttpResponse(html)
All columns
cursor.execute("SELECT * FROM user")
All rows:
cursor.fetchall()
for row in cursor.fetchall():
html = ...
and there is one more thing it is not about your problem but you should keep in mind while write if
The values 0, None, False all are false for if statement so it's better to write if not cursor.rowcount instead if cursor.rowcount==0
you can use this.
import MySQLdb
import MySQLdb.cursors
def get_db_data(request):
conn = MySQLdb.connect(host="localhost", user="test_user", passwd="test_pwd", db="myproject", cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
cursor.execute("SELECT email_address, mobile_number,id, city, state FROM user")
if cursor.rowcount == 0:
html = "<html><body>There is no Faculty member with id.</body></html>"
else:
htm = "<html><body>"
for row in cursor.fetchall():
html += "Id - {id}, E-Mail address - {email_address}, Mobile Number - {mobile_number}, City - {city}, State {state}. </br>".format(**row)
html += "</body></html>"
return HttpResponse(html)
I am currently trying to run a fairly basic python script on my web server. I've gotten this same error when I try to import something that isn't installed on the server so like
import json
I've ran a basic script on the server before so I know that python can run on it. The script is working in my python IDE without any problems but when I put it into my server, I get a 500 error. Any ideas as to why this is occuring would be much appreciated. My webhost is JustHost.com and it uses the CPanel. I did contact them and they said it was something about my script.
#! /usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "username","password","database")
CUR = db.cursor()
def get_password(username):
sql = "select Password from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()[0]
if result == None:
return "User does not exist"
else:
return result[0]
def get_comment(username):
sql = "select Comments from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User has not updated comment"
else:
return result[0]
def get_email(username):
sql = "select Email from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User does not exist"
else:
return result[0]
def get_longitude(username):
sql = "select Longitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_latitude(username):
sql = "select Latitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_address(username):
sql = "select Address from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update email"
else:
return result[0]
def friends_list(username):
sql = "select all friend from accepted_req where userLoggedIn=%s"
CUR.execute(sql, [username])
result=[]
query = CUR.fetchall()
if query == None:
return "User has no friends"
else:
for friend in query:
result.append(friend[0])
return result
def markers_on_map(username):
friendsList = friends_list(username)
fullFriendsList = []
for friend in friendsList:
UserDictionary = {}
UserDictionary["Username"] = friend
UserDictionary["Comment"] = str(get_comment(friend))
UserDictionary["Latitude"] = get_latitude(friend)
UserDictionary["Longitiude"] = get_longitude(friend)
fullFriendsList.append(UserDictionary)
return fullFriendsList
print "Content-type: text/html\n\n"
print markers_on_map("brock")
I fixed it by making it looks exactly perfect in standards of my webhost. the new script now looks like this
#! /usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost", "username","password","database")
CUR = db.cursor()
def get_password(username):
sql = "select Password from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()[0]
if result == None:
return "User does not exist"
else:
return result[0]
def get_comment(username):
sql = "select Comments from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User has not updated comment"
else:
return result[0]
def get_email(username):
sql = "select Email from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User does not exist"
else:
return result[0]
def get_longitude(username):
sql = "select Longitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_latitude(username):
sql = "select Latitude from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update location"
else:
return result[0]
def get_address(username):
sql = "select Address from Users where Username=%s"
CUR.execute(sql, [username])
result = CUR.fetchone()
if result == None:
return "User did not update email"
else:
return result[0]
def friends_list(username):
sql = "select all friend from accepted_req where userLoggedIn=%s"
CUR.execute(sql, [username])
result=[]
query = CUR.fetchall()
if query == None:
return "User has no friends"
else:
for friend in query:
result.append(friend[0])
return result
def markers_on_map(username):
friendsList = friends_list(username)
fullFriendsList = []
for friend in friendsList:
UserDictionary123 = {}
UserDictionary123["Username"] = friend
UserDictionary123["Comment"] = str(get_comment(friend))
UserDictionary123["Latitude"] = get_latitude(friend)
UserDictionary123["Longitiude"] = get_longitude(friend)
fullFriendsList.append(UserDictionary123)
return fullFriendsList