0

I can't insert data into database using a dynamic query in python script

def execute_query(self, qo):
    query_string = "INSERT INTO " +dep_table+ " (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES (%s, %s, %s, %s, %s, %s, %s)" % ("'CO'","'"+qo.db_src+"'","'"+qo.table_src+"'","'"+qo.table_des+"'","'"+qo.check_func+"'","'"+qo.table_des+"'","'NULL'")+";"
    cursor.execute(query_string)

I got this error:

ERROR: Failed to set dependencies informations : ORA-00933: SQL command not properly ended

The connection to the database is okay, but I can't insert.

10
  • You shouldn't use the % operator to insert values into your SQL. xkcd.com/327 Commented Oct 30, 2019 at 21:41
  • %s as a placeholder in SQL is not the same as the string-formatting parameter in Python Commented Oct 30, 2019 at 21:42
  • query_string = "INSERT INTO " + dep_table + " (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES (%s, %s, %s, %s, %s, %s, %s);", ("CO", qo.db_src, qo.table_src, qo.table_des, qo.check_func, qo.table_des, None). You can't parameterize table names, so you'll need to vet that against the schema of the db separately. Commented Oct 30, 2019 at 21:44
  • I tried using % but the same problem Commented Oct 30, 2019 at 21:45
  • I tried your suggestion, I got ERROR: Failed to set dependencies informations : expecting string, unicode or buffer object Commented Oct 30, 2019 at 21:50

3 Answers 3

1

Drop the semi-colon at the end of the string you are creating / executing.

It shouldn't be part of the SQL statement, rather used in some client tools to indicate the end of a statement so that the client can send it to the database to be executed.

Sign up to request clarification or add additional context in comments.

Comments

1

I found the solution to the problem connection.commit()

Comments

0

You can use format method in Python like below:

def execute_query(self, qo):
    query_string = "INSERT INTO {0} (client, sis, entity_name_1, entity_name_2, flag_dep,process, flag_dep_det) VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7})".format(dep_table, 'CO', qo.db_src, qo.table_src, qo.table_des, qo.check_func, qo.table_des, 'NULL')
    cursor.execute(query_string)

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.