Não consigo gravar as informações no DB - MySQL

3 respostas
R

Boa tarde Galera, não consigo gravar as informações no Banco de Dados, vocês poderiam me ajudar?
Sou estudante ainda e estou com essa dificuldade.
Esse programa é para fins de estudo.
Poderiam me mostrar onde está o erro???
Uso o Mysql para testes...
Outro detalhe é que ele se conecta!

Segue o código:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class Teste extends JFrame implements ActionListener{

	JLabel lblNome, lblDocumento, lblTelefone;
	JTextField txtNome, txtDocumento, txtTelefone;
	JButton btGravar;
	
	
	
	Teste(){
		
		
		super("Teste de BD Oracle");
		setResizable(false);
		setBounds(150,50,315,220);
		getContentPane().setLayout(null);
		
		lblNome = new JLabel("Nome: ");
		lblNome.setBounds(5,5,300,20);
		txtNome = new JTextField();
		txtNome.setBounds(5,30,300,20);
		getContentPane().add(lblNome);
		getContentPane().add(txtNome);
		
		lblDocumento = new JLabel("Documento: ");
		lblDocumento.setBounds(5,55,300,20);
		txtDocumento = new JTextField();
		txtDocumento.setBounds(5,80,300,20);
		getContentPane().add(lblDocumento);
		getContentPane().add(txtDocumento);
		
		lblTelefone = new JLabel("Telefone: ");
		lblTelefone.setBounds(5,105,300,20);
		txtTelefone = new JTextField();
		txtTelefone.setBounds(5,130,300,20);
		getContentPane().add(lblTelefone);
		getContentPane().add(txtTelefone);
		
		btGravar = new JButton("Gravar"); btGravar.addActionListener(this);
		btGravar.setBounds(5,165,300,20);
		getContentPane().add(btGravar);
		
		if(!DB.getConnection()){
	    	JOptionPane.showMessageDialog(null, "Falha na conexão com o Banco de Dados. " +
	    			"\nO driver não foi carregado corretamente.");
	        //System.exit(0);
	    }
		else{
			JOptionPane.showMessageDialog(null, "Conectado ao Banco de Dados.");
		}
		//DB.getConnection();	
		
	}
	
	public static void main(String[] args) {
		JFrame janela = new Teste();
		janela.setDefaultCloseOperation(EXIT_ON_CLOSE);
		janela.setVisible(true);

	}

	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==btGravar){
			 String sql = "INSERT INTO teste (documento,nome,telefone," + 
	            "Values ('" +
	            txtDocumento.getText() + "','" +
	            txtNome.getText() + "','" +
                txtTelefone.getText() + "')";
			 int r = DB.runSQL(sql);
			 if (r==1)
		       {	   
		    	   JOptionPane.showMessageDialog(null,"Operação realizada com sucesso!");
		       }    
			 
		}
		
	}

}
DB
import java.sql.*;
public class DB
{
    public static Connection connection = null;
    public static Statement statement = null;
    public static ResultSet resultSet = null; 
    public static final String DRIVER   = "com.mysql.jdbc.Driver";
    public static final String URL      = "jdbc:mysql://localhost:3306/teste";
    public static final String user     = "root";
    public static final String pass     = "minhasenha";

    /** 
     * método que faz conexão com o banco de dados
     * retorna true se houve sucesso, ou false em caso negativo
     */
    
    
    public static boolean getConnection()
    {
       try
       {
   	      Class.forName(DRIVER);
          connection = DriverManager.getConnection(URL, user, pass);
          statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
          System.out.println("Conectou");
          return true;
       }
       catch(ClassNotFoundException erro)
       {
       	  erro.printStackTrace();
          return false;
       }
       catch(SQLException erro)
       {
       	  erro.printStackTrace();
          return false;
       }
    }
    
    /**
     * Fecha ResultSet, Statement e Connection
     */
    public static void close()
    {
	   closeResultSet();
	   closeStatement();
	   closeConnection();	
	}
	
	private static void closeConnection()
	{
	   try
	   {
	      connection.close();
	      System.out.println("Desconectou");
	   }
	   catch(SQLException erro)
	   {
	      erro.printStackTrace();
	   } 
	}  

	private static void closeStatement()
	{
	   try
	   {
	      statement.close();
	   }
	   catch(Exception e)
	   {
          e.printStackTrace();
       }
	}

	private static void closeResultSet()
	{
	   try
	   {
	      resultSet.close();
	   }
	   catch(Exception e)
	   {
          e.printStackTrace();
	   }
	}
    
    /**
     * Carrega o resultSet com o resultado do script SQL
     */
    public static void setResultSet(String sql)
    {
	   try
	   {
		  resultSet = statement.executeQuery(sql);
	   }
       catch(SQLException erro)
       {
          erro.printStackTrace();
       } 
    }  

    /**
     * Executa um script SQL de atualização
     * retorna um valor inteiro contendo a quantidade de linhas afetadas
     */
    public static int runSQL(String sql)
    {
	   int quant = 0; 
	   try
	   {
		  quant = statement.executeUpdate(sql);
	   }
	   catch(SQLException erro)
	   {
	   	  erro.printStackTrace();
	   } 
       return quant;
	}  
}

3 Respostas

F

Seguinte,

Não olhei direito seu código mas ali na linha 67 o comando SQL está errado, faltou fechar o parênteses antes de declarar os valores dos campos.
Substitua a vírgula final por um parênteses ‘)’ e teste novamente.

Falows…

Elizeu_Santos

cara, pesquise sobre preparedStatment. seu código ali ficou meio…

R

fshima
Só era isso mesmo… ¬¬

Criado 18 de março de 2011
Ultima resposta 18 de mar. de 2011
Respostas 3
Participantes 3