I use Liquibase on Mysql and got a below error when trying create function
Unexpected error running Liquibase: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'in varchar2) return varchar2
is
This is my function file MyFunction.sql:
create or replace function MyFuncion(p_id in varchar2)
return varchar2 is Result varchar2(50);
begin Result := 'bbbb' || p_id;
return(Result); end MyFuncion;
End my changelog
<changeSet author="taibc" id="sqlFile-example2">
<sqlFile dbms="ttdp_thanh, mysql"
encoding="utf8"
endDelimiter="\n/"
path="MyFunction.sql"
relativeToChangelogFile="true"
splitStatements="true"
stripComments="true"/>
<rollback>
DROP Function MyFunction;
</rollback>
</changeSet>
Can you help me ?
Related
I have this mapper:
<insert id="insertBatch" parameterType="java.util.Set">
<foreach collection="filterParameterEntitySet" item="item" separator=";">
INSERT INTO filter_parameter
(
filter_key,
filter_value,
filter_id
)
VALUES
(
#{item.filterKey},
#{item.filterValue},
#{item.filter.id}
)
ON CONFLICT DO NOTHING
</foreach>
</insert>
Whenever I execute it, it throws BadSQLGrammarException:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: 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 'CONFLICT DO NOTHING
**
;
INSERT INTO filter_parameter
f' at line 13**
What could be the problem? I can't figure out where does the syntax error lie!
Try this:
<insert id="insertBatch" parameterType="java.util.Set">
INSERT INTO filter_parameter
(
filter_key,
filter_value,
filter_id
) VALUES
<foreach collection="filterParameterEntitySet" item="item" separator=",">
(
#{item.filterKey},
#{item.filterValue},
#{item.filter.id}
)
</foreach>
ON CONFLICT DO NOTHING
</insert>
So basically, there were 2 mistakes in the query:
The separator, instead of this: separator=";"
I should use this: separator=","
ON CONFLICT DO NOTHING is not valid in mysql and I was using mysql (it's for postgres), so I removed it and added the keyword IGNORE after INSERT to reserve the same functionality
I have a couple of stored procedures that I want to execute as initial setup. So What I have done, placed that stored procedure in data.sql and set the jpa.hibernate.ddl-auto=create.
But on startup of my springboot application, the application is failing with com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException. It means, it is not able to understand the syntax of that procedure, however the same procedure can be executed manually on sql sheet without any problem. So how can I execute it via data.sql
data.sql -
DELIMITER $$
CREATE PROCEDURE `GetStocks`(int_stockcode varchar(20))
BEGIN
DECLARE stock_name VARCHAR(100);
SELECT name FROM stock where stock_code = int_stockcode INTO stock_name;
END $$
DELIMITER ;
error-
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException:
Failed to execute SQL script statement #29 of class path resource [default-data.sql]: DELIMITER $$ CREATE PROCEDURE GetStocks(int_stockcode varchar(20)) BEGIN SELECT * FROM stock where stock_code = int_stockcode; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 GetStocks(int_stockcode varchar(20)) BEGIN SELEC' at line 1
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:491)
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:238)
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:48)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:192)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runDataScripts(DataSourceInitializer.java:128)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.onApplicationEvent(DataSourceInitializer.java:118)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.onApplicationEvent(DataSourceInitializer.java:51)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.publishEventIfRequired(DataSourceInitializedPublisher.java:77)
at org.springframework.boot.autoconfigure.orm.jpa.DataSourceInitializedPublisher.postProcessAfterInitialization(DataSourceInitializedPublisher.java:68)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1775)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:113)
... 75 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 GetStocks(int_stockcode varchar(20)) BEGIN SELEC' at line 1
at sun.reflect.GeneratedConstructorAccessor71.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2444)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
at com.sun.proxy.$Proxy106.execute(Unknown Source)
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:470)
... 90 common frames omitted
For loading and creating the database objects it is better to stick to liquibase or flyway.
Using the following code it is possible to load the stored procedure.
Used a controller to load the stored procedure but it can be a simple class or can be configured via an event listener.
#RestController
public class SqlLoaderController {
#Autowired
DataSource dataSource;
#GetMapping("/load")
public void loadScript() throws Exception
{
ResourceDatabasePopulator resourceDatabasePopulator=new ResourceDatabasePopulator();
resourceDatabasePopulator.setSeparator("DELIMITER");
InputStream is= new ClassPathResource("sql.txt").getInputStream();
resourceDatabasePopulator.addScript(new InputStreamResource(is));
resourceDatabasePopulator.execute(dataSource);
}
}
The DELIMITER is used to distinguish between start and end of two stored procedure or database objects.The sql.txt file
CREATE PROCEDURE GetStocks(int_stockcode varchar(20))
BEGIN
DECLARE stock_name VARCHAR(100);
SELECT 1 FROM dual;
END;
DELIMITER
CREATE PROCEDURE GetStocks1(int_stockcode varchar(20))
BEGIN
DECLARE stock_name VARCHAR(100);
SELECT 1 FROM dual;
END;
DELIMITER
I'm getting a reproducible error when using the Erlang/OTP ODBC driver and mySQL. The error is received only when using odbc:param_query() to call a stored procedure with IN variables. The error occurs only on a consecutive param_query call.
The error is: {error,"[MySQL][ODBC 5.2(a) Driver][mysqld-5.6.37-log]Commands out of sync; you can't run this command now SQLSTATE IS: HY000"}
mySQL documentation says the error is caused when using C code mysql_store_result() and not following it up by mysql_free_result(). I believe this is either a problem with the ODBC driver on Erlang side or me not using the param_query properly.
The simple solution I found is not to use param_query or use a sql_query before each param_query I use.
Full example:
SQL:
DROP PROCEDURE if exists test_stored_procedure;
delimiter |
CREATE PROCEDURE `test_stored_procedure`(IN n INT)
BEGIN
SELECT 1;
END
| delimiter ;
Erlang:
-module(odbc_test).
-compile(export_all).
connect() ->
{ok, Conn} = odbc:connect("DSN=myodbc", []),
Conn.
do_param_query(Conn, N) ->
odbc:param_query(Conn, "Call test_stored_procedure(?);", [{sql_integer, [N]}]).
do_sql_query(Conn, N) ->
odbc:sql_query(Conn, "Call test_stored_procedure("++ integer_to_list(N)++");").
Test:
96> odbc:start().
ok
97> Conn = odbc_test:connect().
<0.237.0>
98> odbc_test:do_param_query(Conn,3).
{selected,["1"],[{"1"}]}
99> odbc_test:do_param_query(Conn,3).
{error,"[MySQL][ODBC 5.2(a) Driver][mysqld-5.6.37-log]Commands out of sync; you can't run this command now SQLSTATE IS: HY000"}
100> odbc_test:do_param_query(Conn,3).
{error,"[MySQL][ODBC 5.2(a) Driver][mysqld-5.6.37-log]Commands out of sync; you can't run this command now SQLSTATE IS: HY000"}
101> odbc_test:do_sql_query(Conn,3).
[{selected,["1"],[{"1"}]},{updated,0}]
102> odbc_test:do_param_query(Conn,3).
{selected,["1"],[{"1"}]}
103> odbc_test:do_param_query(Conn,3).
{error,"[MySQL][ODBC 5.2(a) Driver][mysqld-5.6.37-log]Commands out of sync; you can't run this command now SQLSTATE IS: HY000"}
Please advise if you know what is causing the error.
SELECT `template_id`, replace(template_code,"AT -","DE -") as
template_code, `template_text`, `template_styles`, `template_type`,
`template_subject`, `template_sender_name`, `template_sender_email`,
`added_at`, `modified_at`, `orig_template_code`, `orig_template_variables`
FROM `core_email_template` WHERE template_code like "%AT - %"
This query it works and returns me some data that I want to export it. But when I do that from phpmyadmin I received this error:
Error reading data: (#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the
right syntax to use near 'FROM WHERE
(`core_email_template`.`template_id` = 27) OR (`core_email_template' at
line 1)
What should I have to do to make this work ? thx
This is my Code of Stored Function:
CREATE DEFINER=`root`#`localhost` FUNCTION `func`()
RETURNS int(11)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE total INT DEFAULT 0;
select count(*) INTO total from students;
RETURN total;
END
Java Code:
query=em.createNativeQuery("{ SELECT func() }");
String s=(String) query.getSingleResult();
System.out.println(s);
But ir gives an Exception:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '{ SELECT func() }' at line 1
Error Code: 1064
Call: { SELECT func() }
Query: DataReadQuery(sql="{ SELECT func() }")
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '{ SELECT func() }' at line 1
Error Code: 1064
Call: { SELECT func() }
Query: DataReadQuery(sql="{ SELECT func() }")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:377)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getSingleResult(QueryImpl.java:516)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:400)
at org.ceynamon.oregano.datamigration.Test.main(Test.java:26)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
The braces around SELECT funct() are not needed