我需要在SQLAlchemy中创建一个BEFORE INSERT trigger:
DELIMITER |
CREATE TRIGGER set_rank BEFORE INSERT ON authors
FOR EACH ROW BEGIN
IF NEW.rank = 0 THEN
SET NEW.rank = (SELECT IFNULL(MAX(a.rank),0) + 1
FROM authors AS a
WHERE a.id = NEW.pub_id);
END IF;
END |
DELIMITER ;
在mysql-workbench中执行代码工作正常,但在我的实际代码中执行时会出现“你的SQL语法中有错误”异常:
from sqlalchemy.sql.expression import text
connection = db.session.connection()
text(..., connection).execute();
正常运行SELECT SLEEP(1)
,CREATE TABLE test (id INT)
甚至USE some_db
。
这是我收到的mysql错误消息:
(1064,“你的SQL语法有错误; ...'DELIMITER附近| \ n \ n \ n \ n创建TRIGGER set_rank BE ...”)
我很确定我错误地使用了DELIMITER。在这个上下文/如何解决我的问题中,正确的语法是什么?
答案 0 :(得分:11)
你真的不需要DELIMITER
。这只适用于命令行客户端。作为程序员,你将分割语句,否则分隔符将被忽略。
>>> from sqlalchemy import *
>>>
>>> trigger_text = """
... CREATE TRIGGER set_rank BEFORE INSERT ON authors
... FOR EACH ROW BEGIN
... IF NEW.rank = 0 THEN
... SET NEW.rank = (SELECT IFNULL(MAX(a.rank),0) + 1
... FROM authors AS a
... WHERE a.id = NEW.pub_id);
... END IF;
... END
... """
>>>
>>> metadata = MetaData()
>>> authors = Table("authors", metadata,
... Column("id", Integer, primary_key=True),
... Column("rank", Integer),
... Column("pub_id", Integer))
>>>
>>> engine = create_engine("mysql://root@127.0.0.1/test", echo=True)
>>> authors.create(engine)
2012-05-04 17:11:41,093 INFO sqlalchemy.engine.base.Engine
CREATE TABLE authors (
id INTEGER NOT NULL AUTO_INCREMENT,
rank INTEGER,
pub_id INTEGER,
PRIMARY KEY (id)
)
2012-05-04 17:11:41,093 INFO sqlalchemy.engine.base.Engine ()
2012-05-04 17:10:51,376 INFO sqlalchemy.engine.base.Engine COMMIT
>>> engine.execute(trigger_text)
2012-05-04 17:11:41,159 INFO sqlalchemy.engine.base.Engine
CREATE TRIGGER set_rank BEFORE INSERT ON authors
FOR EACH ROW BEGIN
IF NEW.rank = 0 THEN
SET NEW.rank = (SELECT IFNULL(MAX(a.rank),0) + 1
FROM authors AS a
WHERE a.id = NEW.pub_id);
END IF;
END
2012-05-04 17:11:41,159 INFO sqlalchemy.engine.base.Engine ()
2012-05-04 17:11:41,312 INFO sqlalchemy.engine.base.Engine COMMIT
<sqlalchemy.engine.base.ResultProxy object at 0x2be1ed0>
>>>