Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execute .sql file in python
#1
Hello,

I am trying to execute .sql file using python, I am using pymysql.

This is the code I am using to parse sql query

def parse_sql(filename):
    data = open("./ms.sql", 'r').read()
    stmts = []
    DELIMITER = ';'
    stmt = ''
    tab ='\t'

    for lineno, line in enumerate(data):
        if not line.strip():
            continue

        if line.startswith('--'):
            continue

        if 'DELIMITER' in line:
            DELIMITER = line.split()[1]
            continue

        if (DELIMITER not in line):
            stmt += line.replace(DELIMITER, ';')
            continue

        if 'tab' in line:
            tab=line.split()[1]
            continue


        if stmt:
            stmt += line
            stmts.append(stmt.strip())
            stmt = ''
        else:
            stmts.append(line.strip())
    return stmts
I using this definition in such a way

mysql_conn = mysql_getConn('mydb') stmts = parse_sql('my_sql_file.sql')
print(stmts)
with mysql_conn.cursor() as cursor:
    for stmt in stmts:
        cursor.execute(stmt)
    mysql_conn.commit()
My sql query is

SELECT OUTLET_ID,PRODUCT_KEY,DATE_FILTER,CAST(ACCT_SUM_PROD AS SIGNED)/CAST(ACCT_AGG_SUM AS SIGNED) share
FROM
(
SELECT DISTINCT L1.OUTLET_ID,L1.PRODUCT_KEY,L1.DATE_FILTER,SUM(L1.UNITS) OVER(PARTITION BY L1.OUTLET_ID,L1.PRODUCT_KEY,L1.DATE_FILTER) ACCT_SUM_PROD,
SUM(L1.UNITS) OVER(PARTITION BY L1.OUTLET_ID,L1.DATE_FILTER) ACCT_AGG_SUM
FROM
(
SELECT DISTINCT OUTLET_ID,PRODUCT_KEY,CAST(UNITS AS SIGNED) UNITS,
CASE WHEN PERIOD_ID <= '20180630' THEN 'PREV 6M' ELSE 'CURR 6M' END AS DATE_FILTER
FROM weekly
) L1
) L2;
I am getting the error near partition by, I am running my python code in Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-142-generic x86_64)

Error message is below

Traceback (most recent call last):
  File "test_jsonpick.py", line 67, in <module>
    cursor.execute(stmt)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 165, in execute
    result = self._query(query)
  File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 321, in _query
    conn.query(q)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 860, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1061, in _read_query_result
    result.read()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1349, in read
    first_packet = self.connection._read_packet()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1018, in _read_packet
    packet.check_error()
  File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 384, in check_error
    err.raise_mysql_exception(self._data)
  File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 107, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY L1.OUTLET_ID,L1.PRODUCT_KEY,L1.DATE_FILTER)ACCT_SUM_PROD,\nSUM(L1.U' at line 5")
I didnt unserstand whether its a Mysql error or SQL file formatting issue. Is there any other way to acheive this? Thanks in advance!!
Reply
#2
It doesn't look like an error from the python layer. You could try to run the query from a mysql client independently from python to see if it works.
Reply
#3
Hello,

I modify your code and it goes well now.

try this:

def parse_sql(sql_file_path):
    with open(sql_file_path, 'r', encoding='utf-8') as f:
        data = f.read().splitlines()
    stmt = ''
    stmts = []
    for line in data:
        if line:
            if line.startswith('--'):
                continue
            stmt += line.strip() + ' '
            if ';' in stmt:
                stmts.append(stmt.strip())
                stmt = ''
    return stmts
Reply
#4
hmmm... been awhile working with MySQL, can't remember exactly when did they support OVER() clause. I hope the API already implemented.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Failed to execute child process (No such file or directory) uriel 1 1,649 Sep-15-2022, 03:48 PM
Last Post: Gribouillis
  How To Set Up And Execute A Python File knight2000 4 1,891 May-31-2022, 10:02 AM
Last Post: Larz60+
  execute python script guy7200 1 1,590 Oct-25-2021, 09:55 PM
Last Post: Axel_Erfurt
  Possible to execute a python script before log off/shutdown with input commands? Kaltex 1 2,257 May-18-2021, 06:31 AM
Last Post: Skaperen
  Using python to execute app or cmd that requires admin credentials thewolf 0 2,102 Mar-05-2021, 08:15 PM
Last Post: thewolf
  Using a .bat file to execute simple anaconda commands in Windows 10 gacg1 0 4,672 Nov-30-2020, 03:24 PM
Last Post: gacg1
  Execute DBCC CHECKDB from python script susja 1 2,099 Aug-12-2020, 02:09 AM
Last Post: susja
  Trying to write and execute first Python script garvind25 3 2,889 May-23-2020, 07:36 PM
Last Post: garvind25
  How to assess elapsed time to execute a .exe file or opening a desktop application? Sudershan 2 2,129 Apr-18-2020, 01:40 PM
Last Post: buran
  How to execute Python code leemao 2 2,150 Dec-21-2019, 02:35 PM
Last Post: leemao

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020