Skip to content
Advertisement

How to store column value from mysql to python variable?

actually i’m new to learning python and mysql database i have table named TABEL_NILAI in database like this:

JavaScript

So i want to Retrieve value NILAI_TRUST from TABEL_NILAI and i want to do some math. here’s code i was made:

JavaScript

And giving me error like:

JavaScript

so how to retrieve value into python variable in right ways. Please help:(

Advertisement

Answer

The query

JavaScript

will return a iterable of tuples, for example like this:

JavaScript

So this line

JavaScript

has two problems:

  • x is a tuple, so it can’t be called like x()
  • x is not a string, so it doesn’t have a split method

It looks like you want to make TrustValue a list of the int values of each result in the query. In that case this for loop is unnecessary, because it will only it will make the code operate on a single result at a time:

JavaScript

The hitung_standardeviasi function could begin like this:

JavaScript

We can make this code a more readable by looping over the results directly instead of using the for i in range(len(collection)): idiom, which is often unnecessary in Python:

JavaScript

Using a list comprehension is even more Pythonic:

JavaScript

You might want to look at the sum built-in function and the statistics module too.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement