0

I am trying to insert values name and dirname into mysql table using sqlalchemy. The value is the variable I fetch from previous looping function.

My code is:

#loop function to get the value
for filenames in [file for file in inbound_files if file.endswith('.json')]:
    jobname ="Activity A"

    dirname_tup =  [x for x in source_folder.split("/") if x != ''][-1].upper(), 
    #convert tuple to str
    def convertTuple(tup):
        str = ''.join(tup)
        return str

    dirname = convertTuple(dirname_tup)

    sql = f'''
insert into table
(jobname,directoryname)
values 
'{jobName}','{dirname} as directoryname ';
'''
    updateSQL = pd.read_sql(sql,my_conn)

However I received the following error:

sqlalchemy.exc.ProgrammingError: (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 ''Activity A','A_2022' as directoryname' at line 4")
[SQL: 
insert into LISTING_AUDIT_CHECK
(jobname,directoryname)
values 
'Activity A','A_2022' as directoryname;
]

I assumed I have wrongly create the sql statement using sqlalchemy. Appreciate any idea to resolve the issue.

2
  • Have you tried using values ('{jobname}', '{dirname}');? Commented Oct 15, 2022 at 22:21
  • I've tried ('{jobname}','{dirname}' as directoryname); .and received error "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 'as dirname)' .. how do i create an alias for the column dirname here? another try, ('{jobname}','{dirname} as directoryname'); , returns error .. sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. Commented Oct 15, 2022 at 22:32

1 Answer 1

1

an INSERt has no alias, so it produces an error. further the one INSERT mathod

INSERT INTO  tablenames VALUES ('col11','col2')

The values need parenthesis

#loop function to get the value
for filenames in [file for file in inbound_files if file.endswith('.json')]:
    jobname ="Activity A"

    dirname_tup =  [x for x in source_folder.split("/") if x != ''][-1].upper(), 
    #convert tuple to str
    def convertTuple(tup):
        str = ''.join(tup)
        return str

    dirname = convertTuple(dirname_tup)

    sql = f'''
insert into table
(jobname,directoryname)
values 
('{jobName}','{dirname}');
'''
    updateSQL = pd.read_sql(sql,my_conn)
Sign up to request clarification or add additional context in comments.

Comments

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.