此代码在MYSQLWorkbench中正常工作。
use MYDB
drop trigger if exists mytrigger
delimiter //
CREATE TRIGGER mytrigger BEFORE INSERT ON MYTABLE FOR EACH ROW
BEGIN
IF (select COUNT(*) from MYTABLE) = 12 THEN
SET NEW.COL2 = 10;
END IF;
END;//
delimiter ;
MYTABLE有两列(COL1,COL2)
我想通过python创建这个触发器,所以我在python中编写这段代码:
import mysql.connector
cnx = mysql.connector.connect(user='root', password='root', host='127.0.0.1', database='mysql')
cursor = cnx.cursor()
DB_NAME = 'MYDB'
Table_Name= 'MYTABLE'
cursor.execute("CREATE DATABASE IF NOT EXISTS " + str(DB_NAME))
cnx.commit()
cursor.execute("USE " + str(DB_NAME))
cnx.commit()
cursor.execute("CREATE TABLE IF NOT EXISTS " + str(Table_Name) + " ("
" `COL1` BIGINT(20) NOT NULL ,"
" `COL2` varchar(20) NOT NULL,"
" PRIMARY KEY (`COL1`)"
") ENGINE=InnoDB")
cnx.commit()
cursor.execute(" drop trigger if exists mytrigger")
qrystr = (" delimiter // \n"
" CREATE TRIGGER mytrigger BEFORE INSERT ON MYTABLE FOR EACH ROW \n"
" BEGIN \n"
" IF (select COUNT(*) from MYTABLE) = 12 THEN \n"
" SET NEW.COL2 = 10;\n"
" END IF;\n"
" END;//\n"
" delimiter ; \n")
cursor.execute(qrystr)
cnx.commit()
cnx.close()
但是会出现这样的错误:((((((((((((((((((((((((((((((
错误:您的SQL语法出错;检查与您的MySQL服务器版本对应的手册,以便在'分隔符//附近使用正确的语法 在插入第1行的“每行”之前创建触发器mytrigger
请帮助
答案 0 :(得分:0)
对于遇到此问题的其他任何人(或者偶然地在11个月后仍是问询者仍然会遇到的问题):
DELIMITER
仅是CLI的功能(不是服务器本身),因此各种连接器都不知道如何处理它。最后,我删除了DELIMITER
语句和所有依赖它的内容,并将整个触发器语句移到一行以立即执行,从而解决了同样的问题。因为都是一次执行,所以连接器确定分号不会结束该语句。
cursor.execute(" drop trigger if exists mytrigger")
## NEW CODE ##
qrystr = "CREATE TRIGGER mytrigger BEFORE INSERT ON MYTABLE FOR EACH ROW BEGIN IF (select COUNT(*) from MYTABLE) = 12 THEN SET NEW.COL2 = 10; END IF; END"
##############
cursor.execute(qrystr)
cnx.commit()
cnx.close()