0

When I query my MySQL Database I get some extra characters that I don't want. For example, instead of getting 165 I get (165), so, I tried the following in order to extract the number.

The problem is that instead of getting only the number, my code will print nothing, I can't find the reason. Any advice?

 arr = ''

    num = re.findall('\d+', arr)

    mydb = mysql.connector.connect(
        host="localhost",
        user="root",
        database="diff"
    )

    mycursor = mydb.cursor()

    mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
    myresult = mycursor.fetchall()

    for x in myresult:
        arr = x        
        print(arr)
2
  • It seems that myresult is empty. Use a debugger or print statements to see which statements are being executed. Commented Nov 17, 2018 at 20:52
  • Also the first 2 lines are strange. num will be empty is not used. You maybe want to use the compile method in re to create a regex object. e.g. pattern = re.compile("\d+") and call pattern.findall(x) in the loop. Commented Nov 17, 2018 at 20:54

3 Answers 3

2

something like this maybe:

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="Bellini10-",
    database="diff"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
myresult = mycursor.fetchall()

pattern = re.compile("\d+") 

for x in myresult:
    num = pattern.findAll(x)[0]       
    print(num)
Sign up to request clarification or add additional context in comments.

1 Comment

I did not think about it. Thanks for answering!
1

most Python database connectors I've used give back tuples, you'd thus want to do:

for (x,) in myresult:
  print(x)

and you should get what you want

the docs I get suggest you can also just the cursor an iterable context manager, thus something like:

with mydb.cursor() as cur:
  cur.execute("SELECT * FROM val ORDER BY num DESC LIMIT 1")
  for (x,) in cur:
    print(x)

would be more idiomatic Python

1 Comment

This makes sense. Thanks!
1

Try this:

whitelist = set('0123456789')
num = ''.join(filter(whitelist.__contains__, arr))

Hope this helps!

1 Comment

No problem - glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.