I want to read my sql database values and assign them in to variables which I will be using for further processing.
import mysql.connector
mydb = mysql.connector.connect(
host='x.x.x.x',
user="admin",
password="secret",
database="dbname"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM dbname.bb_users")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The following values are returned from my DB:
(78, 0, 2, b'', 0, '63.15.172.56', 1646404832, '[email protected]', Itally, 1646404832, 1646404873, 1646404832, 0, 'viewmc.php')
(79, 0, 2, b'', 0, '10.76.234.152', 1646988672, '[email protected]', India, 1646988672, 1646989676, 1646988672, 1646988813, 'viewtp.php')
(80, 0, 2, b'', 0, '63.14.61.115', 1648820721, '[email protected]', France, 1648820721, 1648820721, 1648820721, 0, 'viewrc.php')
(81, 0, 2, b'', 0, '63.15.190.171', 1648820770, '[email protected]', London, 1648820770, 1648821169, 1648820770, 0, 'view.php')
(82, 0, 2, b'', 0, '63.15.189.113', 1648821062, '[email protected]', America, 1648821062, 1648821598, 1648821062, 1648821181, 'purge.php')
(83, 0, 2, b'', 0, '63.13.134.216', 1649430673, '[email protected]', China, 1649430673, 1649701711, 1649430673, 1649701685, 'view.php')
I would want to read every 6th (IP Address), 8th (email), and 9th (country) values separated by comma and assign to the below variables
IP Address = 6th value, Email = 8th value, Location = 9th value
CodePudding user response:
Note that myresult contains a list of tuples. You can accessing multidemnsional arrays like this: (one example)
first specify the tuple you want to access:
tuple_of_interest = myresult[n] #n is the indexnumber of the element
then you want access the elements in the tuple:
ip = tuple_of_interest[5]
e_mail = tuple_of_interest[7]
country = tuple_of_interest[8]
keep in mind indexing starting at 0...
CodePudding user response:
(78, 0, 2, b'', 0, '63.15.172.56', 1646404832, '[email protected]', Itally, 1646404832, 1646404873, 1646404832, 0, 'viewmc.php')
Are you sure your database gave you Itally
with a typo and not between ''
?
You can access your tuple
s this way:
for my_tuple in myresult:
ip = my_tuple[7]
email = my_tuple[9]
location = my_tuple[10]
And maybe save the data into a list
of dict
ionaries?
res: list[dict[str, int | str]] = []
for my_tuple in myresult:
res.append({
'ip' = my_tuple[7],
'email' = my_tuple[9],
'location' = my_tuple[10]
})
Then you will be able to access res
like this:
>>> # Lets say you want the ip of the 4th user...
>>> res[3]['ip']
1648820770