Python CGI error trying to execute a sqlite command - python

I'm not sure why it says that the table ajax_exmaple does not exist... I check sqlite3 to see that the database and the tables along w/ their corresponding datas are all there. Any ideas?
When I try to execute this command:
query_result = c.execute(query, (sex, age, wpm))
...I get:
<class 'sqlite3.OperationalError'>: no such table: ajax_example
args = ('no such table: ajax_example',)
message = 'no such table: ajax_example'
This is my complete code:
#!C:\python27\python.exe
import cgi, cgitb, sqlite3
cgitb.enable()
print "Content-type: text/html"
print ""
conn = sqlite3.connect('../htdocs/ajax_ex.db')
c = conn.cursor()
# Capture URL query
form = cgi.FieldStorage()
age = form.getvalue('age')
sex = form.getvalue('sex')
wpm = form.getvalue('wpm')
# Build SQL
query = "SELECT * FROM ajax_example WHERE ae_sex = ?"
if(isinstance(age, int)):
query += " AND ae_age <= ?"
if(isinstance(wpm, int)):
query += " AND ae_wpm <= ?"
# Execute query
query_result = c.execute(query, (sex, age, wpm))
conn.close()
# Build result string
display_string = '''
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>WPM</th>
</tr>'''
# Insert a new row in the table for each person returned
for row in query_result:
display_string += "<tr>"
display_string += "<td>row['ae_name']</td>"
display_string += "<td>row['ae_age']</td>"
display_string += "<td>row['ae_sex']</td>"
display_string += "<td>row['ae_wpm']</td>"
display_string += "</tr>"
print "Query: ", query, "<br>"
display_string += "</table>"
print display_string

Related

How to use query params in cases where we need to construct the query manually?

I'm using Python 2 and have the following code:
with conn.cursor() as cursor:
info("Updating {} records".format(len(records_to_update)))
for record in records_to_update:
query = "UPDATE my_table SET "
params_setters = []
# Process all fields except wsid when updating
for index, header in enumerate(DB_COLUMNS_IN_ORDER[1:]):
if record[index] is not None:
params_setters.append("{} = '{}' ".format(header, record[index]))
query += " , ".join(params_setters)
query += " WHERE id = '{}'".format(record[0])
cursor.execute(query)
How can I use query params for escaping here and not have to do it manually in places like:
params_setters.append("{} = '{}' ".format(header, record[index]))
If I understand your question, you want to use a prepared statement. If you are using a driver where %s is used to represent a query parameter (SQLite uses ?), then:
with conn.cursor() as cursor:
info("Updating {} records".format(len(records_to_update)))
params = []
for record in records_to_update:
query = "UPDATE my_table SET "
params_setters = []
# Process all fields except wsid when updating
for index, header in enumerate(DB_COLUMNS_IN_ORDER[1:]):
if record[index] is not None:
params_setters.append("{} = %s ".format(header))
params.append(record[index])
query += " , ".join(params_setters)
query += " WHERE id = %s"
params.append(record[0])
cursor.execute(query, params)

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

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 can't delete data multiple in mysql from python

I made input 2 value row and num when input data so program throw Rollback not work if-else and thank for help
#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
row = raw_input("InputNameRow : ")
num = int(input("InputNumber 1-10 : "))
if num <= 10:
sql1 = "SELECT * FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE '%s' = '%d' " %(row,num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
print "Input Error"
conn.close()
Try :
cursor.execute(sqlde)
instead of
cursor.execute(sqlde, (num))

If value true but null not work

I made program is input number and delete data in mysql. but run program error then report sql1 Syntax Error\i change true
#!/usr/bin/python
import mysql.connector
conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()
try:
num = int(input("InputNumber 1-10 : "))
if num <= 10:
if num == null: //if null print false
sql1 = "SELECT user1 FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sql1)
data = cursor.fetchall()
print(data[0])
sqlde = "DELETE FROM dt WHERE user1 = '%d' " %(num)
cursor.execute(sqlde, (num))
print "DELETE SUCESS"
conn.commit()
else:
print "Data Empty"
except:
conn.rollback()
conn.close()
num = int(input("InputNumber: ")) <- don't forguet to close it
I'm not sure about the %i, I always see using %d for Integer and %s to strings
But, you also have one problem into your query, SQL Injection
So to avoid this, try something like this
sql1 = "DELETE FROM dt WHERE user1 = ?"
try:
cursor.execute(sql1, (num))
print "DELETE SUCECC"
conn.commit()
except:
conn.rollback()
print "ERROR DELETE"
you can check about question mark here or here and understand why you should bind your values

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?

Categories