How to get multiple rows and columns using mysql db through django - python

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)

Related

MySQL: I don't understand why this is happening?

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!!

Python Unbound Local variabel

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.

How to print value from db in python CGI

I am beginner and trying constantly to print value on web page through cgi-bin but i dont know what i am doing wrong. I gone through different tutorials like:
http://www.inmotionhosting.com/support/website/python/how-to-use-python-to-connect-to-a-database
http://ianhowson.com/a-quick-guide-to-using-mysql-in-python.html
http://www.tutorialspoint.com/python/python_database_access.htm
and some threads as well like: Returning Output of Python CGI MySQL Script because i think i am doing wrong somewhere but fail to print.
here is my code and it only prints "hello":
#!C:\Python27\python.exe
import cgi
import cgitb
print "Content-type: text/html\n"
print """
<html>
<head>
<p> hello</p>
</head>
"""
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1",port=3306, user="root", passwd="",db="project")
cursor = db.cursor()
cursor2 = db.cursor()
# execute SQL select statement
#sql = "SELECT stid,firstname FROM student WERE stid IN(SELECT stid FROM stobt WHERE stid=%s" % (0)
sql2 = "SELECT stid FROM student WHERE firstname = '%s'" % ('User')
# Execute the SQL command
cursor2.execute(sql2)
# Fetch all the rows in a list of lists.
result2 = cursor2.fetchall()
#print result2
row2 = result2[0]
#print 'r1',row[1]
#print 'r2',row2[0]
sql = "SELECT * FROM stobt WHERE stid = '%d'" % (row2)
cursor.execute(sql)
results = cursor.fetchall()
row = results[1]
tc = 56
for row in results:
if row2[0] == row[1]:
idd = row[0]
stid = row[1]
obtained = row[2]
subject = row[3]
# Now print fetched result
print( "<h1>id=%s,stid=%s,obtained=%f,subject=%s</h1>" %(idd, stid, obtained, subject ))
print """
<body>
<p> idd</p>
</body>
</html>
"""
# if obtained <= 50:
# if tc >= 50:
# print tc
db.close()
Any idea?

Python script 500 error

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

MysqlDb and Pyqt4 comparing variables

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'

Categories