我正在尝试插入客户。
当我从executeUpdate打印字符串,复制并粘贴到mysql上时,数据插入没有问题。
异常的描述如下:
Exception in thread "main" 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 'update cliente set honorarioMensal = 2000.2 where cnpj = 'cnpj_ex'' at line 2
有人可以帮助我吗?
public class Teste {
public static void main(String[] args) throws SQLException {
try {
Industria industria = IndustriaDB.getById(1);
System.out.println(industria);
Funcionario funcionario = new Funcionario("Func1","Func1");
funcionario.setCustoMensal(22);
Cliente cliente = new Cliente("cnpj_ex", "nome_ex",industria);
cliente.setPreco((float) 2000.2);
System.out.println(cliente);
System.out.println(cliente.getFuncionario());
ClienteDB.inserir(cliente);
ClienteDB.deletar(cliente);
} catch (ContexataException ge) {
System.out.println("---> " + ge.getMessage());
System.out.println("---> Detalhamento do erro: ");
ge.printStackTrace();
} finally {
}
}
}
public class ClienteDB extends Conexao{
public static void inserir(Cliente cliente) throws ContexataException, SQLException, NullPointerException {
Connection conn = Conexao.getConnection();
try {
String createString =
"INSERT into cliente "
+ "(cnpj, nome, id_Industria) "
+ "values('" + cliente.getCnpj() + "','"
+ cliente.getNome() + "',"
+ cliente.getIndustria().getId() + ");";
if (cliente.getFuncionario() != null){
createString = createString + "\n update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + "\n update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
System.out.println("SQL: " + createString);
executeUpdate(conn, createString);
System.out.println("Novo cliente inserido!\n");
// } catch (SQLException e) {
// throw new ContexataException("Erro ao inserir novo cliente.");
} catch (NullPointerException e) {
throw new ContexataException("Alguns dados não foram preenchidos suficientemente para o banco de dados!");
} finally {
Conexao.closeAll(conn);
}
}
public class Cliente { // only the atributes are necessary...
private String cnpj;
private String nome;
private float preco;
private Industria industria;
private Funcionario funcionario;
// getter and setter...
最佳答案
问题出在查询字符串中的 \n
个字符。您不应该使用它们,请检查您的代码并删除无效字符。
if (cliente.getFuncionario() != null){
createString = createString + " update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + " update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
并且您不能在 insert
语句中编写update
。
关于在 mysql 中运行的字符串上的 Java SQLException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27948731/