简体   繁体   English

使用python执行Mysql存储过程

[英]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.我有一个在 python 中使用 mysql 游标时不执行的存储过程语句,但它可以在任何其他 Mysql 查询工具(如工作台或 navicat)上执行。 I have successfuly connected to my database that contains a table called users.我已成功连接到包含名为 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

DELIMITER is command-line client's command, not SQL statement. DELIMITER是命令行客户端的命令,而不是 SQL 语句。 Do not use it in SQL code.不要在 SQL 代码中使用它。

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.在您的特定情况下,存储过程包含一个 SQL 语句,因此它可以在没有 BEGIN-END 块的情况下使用单个语句创建,并且即使在 CLI 中也不需要在 DELIMITER 中重新分配。 Ie simply即简单地

CREATE PROCEDURE GetAllUsers() 
SELECT *  FROM users;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM