博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Create function through MySQLdb
阅读量:6670 次
发布时间:2019-06-25

本文共 2267 字,大约阅读时间需要 7 分钟。

http://stackoverflow.com/questions/745538/create-function-through-mysqldb

 

How can I define a multi-statement function or procedure in using the MySQLdb lib in python?

Example:

import MySQLdbdb = MySQLdb.connect(db='service') c = db.cursor() c.execute("""DELIMITER // CREATE FUNCTION trivial_func (radius float) RETURNS FLOAT BEGIN IF radius > 1 THEN RETURN 0.0; ELSE RETURN 1.0; END IF; END // DELIMITER ;""")

Which creates the following traceback:

Traceback (most recent call last): File "proof.py", line 21, in 
DELIMITER ;""") File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 173, in execute File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 35, in defaulterrorhandler _mysql_exceptions.ProgrammingError: (1064, "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 //\nCREATE FUNCTION trivial_func (radius float) \n RETURNS FLOAT\n\n ' at line 1")

If I copy the same SQL directly into a mysql shell client, it works as expected

 
 

3 Answers

15accepted

The DELIMITER command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use DELIMITER if you execute SQL statements directly through an API.

The purpose of DELIMITER is to help you avoid ambiguity about the termination of the CREATE FUNCTION statement, when the statement itself can contain semicolon characters. This is important in the shell client, where by default a semicolon terminates an SQL statement. You need to set the statement terminator to some other character in order to submit the body of a function (or trigger or procedure).

CREATE FUNCTION trivial_func (radius float) RETURNS FLOAT BEGIN IF radius > 1 THEN RETURN 0.0; <-- does this semicolon terminate RETURN or CREATE FUNCTION? ELSE RETURN 1.0; END IF; END

Since the API typically allows you to submit one SQL statement at a time, there's no ambiguity -- the interface knows that any semicolons inside the body of your function definition don't terminate the whole CREATE FUNCTION statement. So there's no need to change the statement terminator with DELIMITER.

转载地址:http://twlxo.baihongyu.com/

你可能感兴趣的文章
PHP框架认识初步
查看>>
给 Android 初学者的 Gradle 知识普及
查看>>
分模块开发创建Action子模块——(九)
查看>>
基于Nginx实现一个自己的HTTP模块
查看>>
LeetCode(34)-Palindrome Number
查看>>
阅读《Android 从入门到精通》(24)——切换图片
查看>>
SimpleDateFormat线程不安全及解决的方法
查看>>
Unity---------Mesh理解
查看>>
hdu 1728 逃离迷宫 bfs记转向
查看>>
一分钟学会 ConstraintLayout 之从属性角度理解布局
查看>>
线程 Timer TimerTask 计时器 定时任务 MD
查看>>
[js高手之路]原型式继承与寄生式继承
查看>>
2017“编程之美”终章:AI之战勇者为王
查看>>
[js高手之路]HTML标签解释成DOM节点
查看>>
MBR分区操作-增加、扩展、删除
查看>>
JAVA回调机制(CallBack)详解
查看>>
Linux误删文件后恢复数据
查看>>
Vue学习手札
查看>>
IdentityServer4 通过 AccessToken 获取 UserClaims
查看>>
IIS访问站点,出现connection refused
查看>>