Java SQL说我的语法不正确,但在shell中运行查询是有效的
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java SQL说我的语法不正确,但在shell中运行查询是有效的相关的知识,希望对你有一定的参考价值。
我正在尝试插入我的数据库,但我得到SQLException: Problem in your syntax, line 2
。所以我在运行它之前将查询打印到控制台,然后将其粘贴到SQL shell中,它运行没有问题。我不知道我做错了什么,请帮忙。
Utilizador u = new Aluno("A55555","password","cinco@email.com","Cinco",false,new HashMap<>());
new UserDAO().put(u.getUserNum(),u);
SQL查询产生:
START TRANSACTION;
INSERT INTO `Utilizador` (id, nome,pass, Email)
VALUES ('A55555', 'Cinco', 'password', 'cinco@email.com')
ON DUPLICATE KEY UPDATE id=VALUES(id),
pass=VALUES(pass),
nome=VALUES(nome),
Email=VALUES(Email);
INSERT INTO `Aluno` (Utilizador_id, eEspecial)
VALUES ('A55555',0)
ON DUPLICATE KEY UPDATE Utilizador_id=VALUES(Utilizador_id),
eEspecial=VALUES(eEspecial);
Java的:
String sql = "START TRANSACTION;
" +
"INSERT INTO `Utilizador` (id, nome,pass, Email)
" +
"VALUES (?, ?, ?, ?)
" +
"ON DUPLICATE KEY UPDATE id=VALUES(id),
" +
" pass=VALUES(pass),
" +
" nome=VALUES(nome),
" +
" Email=VALUES(Email);
";
StringBuilder s = new StringBuilder(sql);
if (value instanceof Docente){
s.append("INSERT INTO `Docente` (Utilizador_id)
" +
"VALUES (?)
" +
"ON DUPLICATE KEY UPDATE Utilizador_id=VALUES(Utilizador_id);");
}else if (value instanceof Aluno){
s.append("INSERT INTO `Aluno` (Utilizador_id, eEspecial)
" +
"VALUES (?,?)
" +
"ON DUPLICATE KEY UPDATE Utilizador_id=VALUES(Utilizador_id), eEspecial=VALUES(eEspecial);");
}else if (value instanceof DiretorDeCurso){
s.append("INSERT INTO `DiretorDeCurso` (Utilizador_id)
" +
"VALUES (?)" +
"ON DUPLICATE KEY UPDATE Utilizador_id=VALUES(Utilizador_id);
");
}else{
return null;
}
System.out.println(s.toString());
PreparedStatement stm = connection.prepareStatement(s.toString());
stm.setString(1, value.getUserNum());
stm.setString(2, value.getName());
stm.setString(3, value.getPassword());
stm.setString(4, value.getEmail());
stm.setString(5, value.getUserNum());
if(value instanceof Aluno) stm.setBoolean(6,((Aluno) value).eEspecial());
System.out.println(stm.toString());
stm.executeUpdate();
答案
Statement
和PreparedStatement
用于单个陈述,而不是多个。你必须一次执行一个。
以上是关于Java SQL说我的语法不正确,但在shell中运行查询是有效的的主要内容,如果未能解决你的问题,请参考以下文章