在mysql上使用EntityManager JPA运行脚本 [英] Run script with EntityManager JPA on Mysql

查看:216
本文介绍了在mysql上使用EntityManager JPA运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行脚本(.sql文件),但是由于尝试了很多方法,我遇到了多个错误,这是我的主要sql脚本:

I'm trying to run a script (.sql file) but i have multiples errors since i tried many ways, here's my main sql script:

INSERT INTO `Unity` VALUES (11,'paq',0,'2013-04-15 11:41:37','Admin','Paquete','Paq',0,'2013-04-15 11:41:37','AAA010101AAA',NULL);
INSERT INTO `product` VALUES (11,'chi','USD','chi one',0,'2013-04-15 11:42:13',0,'Admin','Chi name',0.25,0,15,'2013-04-15 11:42:13','AAA010101AAA',NULL);

这是我的主要dao代码:

and here's my main dao code:

@Autowired
private EntityManager em;
@Override
public Integer runSql(String path) {
    try {
        Archivo archivo = new Archivo();
        String strQuery = archivo.readFileText(path);
        Query query = em.createNativeQuery(strQuery);
        return query.executeUpdate();
    } catch (IOException e) {
        e.printStackTrace();
        return 0; //TODO return false;
    }
}

如果我只使用一个插入来运行脚本,则运行正常,但是当我的脚本中有多个插入时,会出现以下异常:

If i run the script with only one Insert it runs ok, but when my script has more than 1 insert i get the following Exception:

您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本以使用正确的语法 在'INSERT INTO producto_servicio VALUES(11,'chi','USD','chi one',0,'2013-04-15 11:42:13',0,''在第2行

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 'INSERT INTO producto_servicio VALUES (11,'chi','USD','chi one',0,'2013-04-15 11:42:13',0,'' at line 2

是否可以运行带有多个插入的脚本文件?

Is there a way to run a script file with multiple inserts?

我也尝试过使用BEGIN,END和START TRANSACTION AND COMMIT,但效果不佳.

I also tried with BEGIN, and END, and START TRANSACTION AND COMMIT, but with no good results.

谢谢您的帮助:)

推荐答案

据我所知,您不能通过em.createNativeQuery执行脚本. 您应该将脚本拆分为语句,然后一个一个地执行它们.

You can't execute the script by the em.createNativeQuery, as i know. You should to split the script into statements and execute them one by one.

您可以使用 ScriptRunner .它可以与MyBatis分开使用.

You may use ScriptRunner. It can be used separately from the MyBatis.

示例:

em.getTransaction().begin();
Connection connection = em.unwrap(Connection.class);
ScriptRunner sr = new ScriptRunner(connection);
sr.runScript(new StringReader("INSERT INTO `Unity` VALUES (11,'paq',0,'2013-04-15 11:41:37','Admin','Paquete','Paq',0,'2013-04-15 11:41:37','AAA010101AAA',NULL);\r\nINSERT INTO `product` VALUES (11,'chi','USD','chi one',0,'2013-04-15 11:42:13',0,'Admin','Chi name',0.25,0,15,'2013-04-15 11:42:13','AAA010101AAA',NULL);"));
em.getTransaction().commit();

这篇关于在mysql上使用EntityManager JPA运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆