I have a php form which saves these values to the database:
- id
- rand (a randomly generated string)
- x_val
- y_val
I am calling these values back from database in a python program using mysqldb:
import MySQLdb
db = MySQLdb.connect("localhost","root","","test" )
cursor = db.cursor()
sql = "SELECT id,rand,x_val,y_val FROM table"
try:
cursor.execute(sql)
results = cursor.fetchall()
results = {}
for row in results:
results[row[1]] = [row[0], row[2], row[3]]
rand = row[1]
x_val = row[2]
y_val = row[3]
except:
print "Error: unable to fecth data"
db.close()
UPDATE: It gives the Error -> Error: unable to fecth data
In this piece (as you can see) i want rand (i.e. row[1]) to serve as the identifier for the row. However, I am not able to find a way about how to use this as an identifier since rand = row[1] is called after the sql variable. In this example, I have used a static '63kfjf' rand value, which is just to show you the working. Is there a way?
2 Answers 2
After selecting your datas from DB, you can create a dictionnary with "rand" value as key:
Something like this:
dicResults = {}
for row in results:
dicResults[row[1]] = [row[0], row[2], row[3]]
Comments
I think you're trying to randomly select a row? If that is correct, this will work.
Change rand to an auto incrementing integer.
SELECT MAX(rand) FROM table; to determine the highest 'random' value.
Generate a random value between 0 and MAX(rand)
SELECT * FROM table WHERE rand = $randomGeneratedValue;
SELECT *is a bad idea. If the order of the columns in your database ever changes your code might break. Better to doSELECT id, rand, x_val, y_val ....