-1

This is a MySQL query that I want to use it inside a python script:

 cmd = "mysql -Nr -uuser -ppwd   -hlocalhost -P3307 mybase -e 'select value from table where Id='5' and product='product'" | tr -d ' ' | tr -d ',' | sed 's/>https:/>\r\nhttps:/g' | sed 's/=</=\n</g' | grep "https:" | sed 's;www.mysite.org/page/;;g'  > /tmp/myfile.tmp"

After the Update it's look like this:

  cmd = "mysql -Nr -uuser -ppwd  -hlocalhost -P3307 mybase -e \' select value from table where Id="5" and product="product" \' | tr -d \' \' | tr -d \',\' | sed \'s/>https:/>\r\nhttps:/g\' | sed \'s/=</=\n</g\' | grep "https:" | sed \'s;www.mysite.org/page/;;g \'  > /tmp/myfile.tmp"

The Result after the execution:

SyntaxError: invalid syntax

[root@admin tmp]$ vi select_python.py

[root@admin tmp]$ python select_python.py

What's wrong with my MySQL query Syntax inside the python script?

Bainim
  • 59
  • 1
  • 3
  • 9
  • It's not about MySQL query. You start your string with `"` and then you are trying to use `"` again inside the string. Python interprets this as the end of the string, so everything after this character is breaking python syntax. But this is the basic problem. First of all this is not how you use MySQL in Python. There are Python libraries for MySQL. – ElmoVanKielmo Sep 17 '18 at 10:32
  • Related https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python?rq=1 – ElmoVanKielmo Sep 17 '18 at 10:40
  • Thank you for your response, it's useful, now i have an other error : **sed: -e expression #1, char 12: unterminated `s' command** and **tr: write error: Broken pipe** – Bainim Sep 17 '18 at 10:44
  • Possible duplicate of [Python string invalid syntax](https://stackoverflow.com/questions/51248467/python-string-invalid-syntax) – ElmoVanKielmo Sep 17 '18 at 10:44
  • 1
    You seem to be using Python only to execute a complicated shell command. Why not do your query, the result processing and file handling directly in Python? – shmee Sep 17 '18 at 11:07
  • now i get this **sed: -e expression #1, char 6: unterminated `s' command** and **ERROR 1054 (42S22) at line 1: Unknown column 'dynamic' in 'where clause'** in the whare clause i'm putting this : **and moduleid='dynamic-file** the issue is about the Hyphen-minus between the where clause value. – Bainim Sep 17 '18 at 13:54

1 Answers1

0

you can use the os package in python to call the mysql query and handle thelinux pipe formatting a simple method would be look like:

import os
os.system("mysql -Nr -uuser -ppwd   -hlocalhost -P3307 mybase -e 'select value from table where Id='5' and product='product'\"  | tr -d ' ' | sed 's/>https:/>\r\nhttps:/g' | sed 's/=</=\n</g' | grep \"https:\" | sed 's;www.mysite.org/page/;;g'  > /tmp/myfile.tmp")

make sure to escape any double quotes