Erro de SQL no JAVA porém quando pego a SQL e jogo direto no servidor ele roda

6 respostas
rcipriani

Então, ta dando um erro de sintaxe, porém quando pego a SQL gerada e jogo no servidor ela roda normalmente…

Segue códigos.

SQL:
DELETE FROM permissaoperfil WHERE idPerfil = 4 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 11 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 8 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 13 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 12 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 9 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 10 ;

ERRO:
com.mysql.jdbc.JDBC4PreparedStatement@10f0625: DELETE FROM permissaoperfil WHERE idPerfil = 4 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 11 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 8 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 13 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 12 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 9 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 10 ;
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 ‘INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 11 ; INSERT’ at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1356)
at br.com.bb.proagro.modelo.PerfisDAO.cadastraPermissoes(PerfisDAO.java:75)
at br.com.bb.proagro.controle.PerfisControle.salvarPermissoes(PerfisControle.java:36)
at br.com.bb.proagro.visao.TelaPerfis.salvar(TelaPerfis.java:87)
at br.com.bb.proagro.visao.TelaPerfis.botaoSalvarActionPerformed(TelaPerfis.java:262)
at br.com.bb.proagro.visao.TelaPerfis.access$300(TelaPerfis.java:31)
at br.com.bb.proagro.visao.TelaPerfis$4.actionPerformed(TelaPerfis.java:170)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3255)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Erro ao inserir no banco de dados: [Ljava.lang.StackTraceElement;@1bc4ec8
com.mysql.jdbc.JDBC4PreparedStatement@10f0625: DELETE FROM permissaoperfil WHERE idPerfil = 4 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 11 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 8 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 13 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 12 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 9 ; INSERT INTO permissaoperfil SET idPerfil = 4, idPermissao = 10 ;
CONSTRUÍDO COM SUCESSO (tempo total: 1 minuto 35 segundos)

CODIGO:

public boolean cadastraPermissoes(ArrayList<PermissoesVO> arrPermissoes, Integer idPerfil){
		
		PreparedStatement pst = null;
		
		//CADSATRANDO AS PERMISSOES
		StringBuilder sql = new StringBuilder();
		//Fazendo a Sql para permissoes, pra ir tudo numa soh
		//apagando todos para colocar novamente
		sql.append(" DELETE FROM `permissaoperfil` " +
				  " WHERE idPerfil = "+idPerfil+" ; ");
		for (PermissoesVO permissoesVO : arrPermissoes) {
			
			sql.append(" INSERT INTO `permissaoperfil` SET " +
					  " `idPerfil` = "+idPerfil+", " +
					  " `idPermissao` = "+permissoesVO.getId()+" ; ");
			
		}

		try {
	
            pst = this.getConnection().prepareStatement(sql.toString());
            System.out.println(pst.toString());
            pst.execute();

//			pst.close();
                return true;
//		}catch (SQLException eSQL) {
//			eSQL.printStackTrace();
		} catch (Exception e) {
                    e.printStackTrace();
			System.err.println("Erro ao inserir no banco de dados: " + e.getStackTrace()+ "\n"+pst.toString());
		}
		return false;
		
	}

Alguém sabe?

6 Respostas

thiago.correa

O SQL pode estar certo mas o uso está incorreto!
Você deve criar um Statement para o delete e outro para o insert!

rcipriani
thiago.correa:
O SQL pode estar certo mas o uso está incorreto! Você deve criar um Statement para o delete e outro para o insert!

Mudei, ele conseguiu deletar, que é a primeira parte, mas pra inserir deu erro:

CODIGO FICOU ASSIM:
public boolean cadastraPermissoes(ArrayList<PermissoesVO> arrPermissoes, Integer idPerfil){
		
		PreparedStatement pst = null;
		PreparedStatement pst2 = null;
		
		//CADSATRANDO AS PERMISSOES
		StringBuilder sql = new StringBuilder();
		StringBuilder sql2 = new StringBuilder();
		
		//Fazendo a Sql para permissoes, pra ir tudo numa soh
		//apagando todos para colocar novamente
		sql.append(" DELETE FROM `permissaoperfil` " +
				  " WHERE idPerfil = "+idPerfil+" ; ");
		for (PermissoesVO permissoesVO : arrPermissoes) {
			
			sql2.append(" INSERT INTO `permissaoperfil` SET " +
					  " `idPerfil` = "+idPerfil+", " +
					  " `idPermissao` = "+permissoesVO.getId()+" ; ");
			
		}

		try {
	
            pst = this.getConnection().prepareStatement(sql.toString());
            pst.execute();
            
            pst2 = this.getConnection().prepareStatement(sql2.toString());
            pst2.execute();
            
//			pst.close();
            return true;
		}catch (SQLException eSQL) {
			eSQL.printStackTrace();
		} catch (Exception e) {
            e.printStackTrace();
			System.err.println("Erro ao inserir no banco de dados: " + e.getStackTrace()+ "\n"+pst.toString());
		}
		return false;
		
	}

ERRO ASSIM:
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 'INSERT INTO `permissaoperfil` SET `idPerfil` = 4, `idPermissao` = 8 ; INSERT ' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1356)
at br.com.bb.proagro.modelo.PerfisDAO.cadastraPermissoes(PerfisDAO.java:79)
at br.com.bb.proagro.controle.PerfisControle.salvarPermissoes(PerfisControle.java:36)
at br.com.bb.proagro.visao.TelaPerfis.salvar(TelaPerfis.java:87)
at br.com.bb.proagro.visao.TelaPerfis.botaoSalvarActionPerformed(TelaPerfis.java:262)
at br.com.bb.proagro.visao.TelaPerfis.access$3(TelaPerfis.java:261)
at br.com.bb.proagro.visao.TelaPerfis$4.actionPerformed(TelaPerfis.java:170)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

EITA :(

thiago.correa

Retire o ponto-e-vírgula e as apas simples do insert/delete, da tua instrução SQL, isso não é necessário!
ao invés de:

String sql = "insert into tabela 'coluna' = " + varialvel + ";";

use

String sql = "insert into tabela coluna = " + varialvel;

Outra coisa, se você quiser inserir em batch (mais de um registro em uma única vez) você deve usar o método addBatch e executeBatch da classe Statement (ou PreparedStatement)

Sugestão de melhoria user o PreparedStatement o seu código ficaria assim

sql.append(" DELETE FROM permissaoperfil  WHERE idPerfil = ?");  
pst = this.getConnection().prepareStatement(sql.toString()); 
pst.setString(1, idPerfil);
pst.execute();
rcipriani
thiago.correa:
Retire o ponto-e-vírgula e as apas simples do insert/delete, da tua instrução SQL, isso não é necessário! ao invés de:
String sql = "insert into tabela 'coluna' = " + varialvel + ";";
use
String sql = "insert into tabela coluna = " + varialvel;

Outra coisa, se você quiser inserir em batch (mais de um registro em uma única vez) você deve usar o método addBatch e executeBatch da classe Statement (ou PreparedStatement)

Sugestão de melhoria user o PreparedStatement o seu código ficaria assim

sql.append(" DELETE FROM permissaoperfil  WHERE idPerfil = ?");  
pst = this.getConnection().prepareStatement(sql.toString()); 
pst.setString(1, idPerfil);
pst.execute();

GRannndee!!

Se eu soubesse disso antes teria poupado tempo nosso!!

Ficou asism o código, pra quem precisar!!

public boolean cadastraPermissoes(ArrayList<PermissoesVO> arrPermissoes, Integer idPerfil){
		
		PreparedStatement pst = null;
		PreparedStatement pst2 = null;
		
		//DELETANDO AS PERMISSOES PARA CADASTRAR DNOVO
		try {
        	String sql = "  DELETE FROM permissaoperfil WHERE idPerfil = ? ; ";
    		pst = this.getConnection().prepareStatement(sql.toString());
    		pst.setInt(1, idPerfil);
            pst.execute();
		} catch (SQLException e) {
			System.err.println("Erro ao deletar no banco de dados: " + e.getStackTrace()+ "\n"+pst.toString());
			e.printStackTrace();
		}
		
		//INSERINDO AS PERMISSOES
		try {
			String sql2 = " INSERT INTO permissaoperfil SET " +
			   " idPerfil = ?, " +
			   " idPermissao = ? ; ";
			pst2 = this.getConnection().prepareStatement(sql2.toString());
			for (PermissoesVO permissoesVO : arrPermissoes) {
				pst2.setInt(1, idPerfil);
				pst2.setInt(2, permissoesVO.getId());
				pst2.addBatch();
	    	}
			pst2.executeBatch();
		} catch (SQLException e) {
			System.err.println("Erro ao inserir no banco de dados: " + e.getStackTrace()+ "\n"+pst.toString());
			e.printStackTrace();
		}
		return true;
	}

Abraço, e obrigado pela ajuda

thiago.correa

Caso o sistema seja alvo de estudo e ou teste, favor desconsiderar essa outra sugestão:

Sugiro você usar somente e.printStackTrace() para efeito de estudos (ou utilizar uma biblioteca de logging)

ou, você pegar a exceção e relançá-la para que o sistema trate e informe o usuário do erro

rcipriani

thiago.correa:
Caso o sistema seja alvo de estudo e ou teste, favor desconsiderar essa outra sugestão:

Sugiro você usar somente e.printStackTrace() para efeito de estudos (ou utilizar uma biblioteca de logging)

ou, você pegar a exceção e relançá-la para que o sistema trate e informe o usuário do erro

Eu trato tudo com Throws na interface de controle, depois que finalizar o programa eu retiro todos…
Sei que o certo era usar uma biblioteca para isso, mas assim acho qeu vai ficar correto também…

Obrigado

Criado 16 de setembro de 2010
Ultima resposta 16 de set. de 2010
Respostas 6
Participantes 2