Search code examples
pythonmysqlsqlcursorprocedure

Executing Mysql stored procedure using python


I have a stored procedure statement that doesnt execute when using mysql cursor in python, but it executes on any other Mysql query Tools such as workbench or navicat. I have successfuly connected to my database that contains a table called users.

    import mysql.connector
    from mysql.connector import Error

    mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    charset='utf8',
    database="story_db"
           )

    mycursor = mydb.cursor()
    query="DELIMITER $$ CREATE PROCEDURE GetAllUsers() BEGIN    SELECT *  FROM users; END $$        
    DELIMITER ;"
    try:
      mycursor.execute(query)
      print("success")
    except Error as err:
      print(err)

I get this error as a result:

1064 (42000): 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 'DELIMITER $$ CREATE PROCEDURE GetAllUsers() BEGIN  SELECT *  FROM users' at line 1

Solution

  • DELIMITER is command-line client's command, not SQL statement. Do not use it in SQL code.

    In your particular case the stored procedure contains ONE SQL-statement, so it may be created without BEGIN-END block, using single statement, and does not need in DELIMITER reassign even in CLI. I.e. simply

    CREATE PROCEDURE GetAllUsers() 
    SELECT *  FROM users;