DAO com função sql

17 respostas
Mariana.Vecci

Gente, to com algumas dúvidas.. rs rs.. help que ta difícil..

a primeira é que o código do usuário é serial, aai não sei como ficaria no java isso, aqui a tabela:
CREATE TABLE Usuario (
  cod_u serial NOT NULL PRIMARY KEY,
  nome_u VARCHAR(30) NOT NULL,
  nick_u VARCHAR(10) NOT NULL,
  email_u VARCHAR(20) NOT NULL,
  pass_u VARCHAR(8) NOT NULL
);
na Classe usuario ficou assim:
package model;

public class Usuario {
	  private String nome_u;
	  private String nick_u; 
	  private String email_u; 
	  private String pass_u;
	  
	public Usuario(String nome_u, String nick_u, String email_u, String pass_u) {
		super();
		this.nome_u = nome_u;
		this.nick_u = nick_u;
		this.email_u = email_u;
		this.pass_u = pass_u;
	}
	
	public String getNome_u() {
		return nome_u;
	}
	public void setNome_u(String nome_u) {
		this.nome_u = nome_u;
	}
	public String getNick_u() {
		return nick_u;
	}
	public void setNick_u(String nick_u) {
		this.nick_u = nick_u;
	}
	public String getEmail_u() {
		return email_u;
	}
	public void setEmail_u(String email_u) {
		this.email_u = email_u;
	}
	public String getPass_u() {
		return pass_u;
	}
	public void setPass_u(String pass_u) {
		this.pass_u = pass_u;
	}
}
Tenho em sql duas funções, uma para inserir, e outra para alterar a password do usuario:
inserir_usuario('fulano','fulaninho','[email removido]','666');
alterar_usuario('fulano','fulaninho','[email removido]','999');
Tem como chamar elas a partir dos botões da tela? aqui está o código da tela do usuário:
package swing;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import model.Usuario;

import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;

import sql.AcessoUsuarioDAO;

//VS4E -- DO NOT REMOVE THIS LINE!
public class Usuario_tela extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JLabel jLabel0;
	private JLabel jLabel2;
	private JLabel jLabel1;
	private JLabel jLabel3;
	private JLabel jLabel4;
	private JLabel jLabel5;
	private JLabel jLabel6;
	private JTextField jTextField1;
	private JTextField jTextField0;
	private JTextField jTextField2;
	private JPasswordField jPasswordField0;
	private JButton jButton0;
	private JButton jButton1;
	private JLabel jLabel7;
	private JLabel jLabel8;
	private JLabel jLabel9;
	private JLabel jLabel10;
	private JTextField jTextField4;
	private JTextField jTextField5;
	private JTextField jTextField6;
	private JTextField jTextField3;
	private JInternalFrame jInternalFrame0;
	private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
	public Usuario_tela() {
		initComponents();
	}

	private void initComponents() {
		setLayout(new GroupLayout());
		add(getJLabel0(), new Constraints(new Leading(243, 10, 10), new Leading(19, 10, 10)));
		add(getJLabel2(), new Constraints(new Leading(435, 10, 10), new Leading(63, 12, 12)));
		add(getJLabel1(), new Constraints(new Leading(45, 10, 10), new Leading(63, 12, 12)));
		add(getJLabel3(), new Constraints(new Leading(12, 12, 12), new Leading(112, 10, 10)));
		add(getJLabel4(), new Constraints(new Leading(12, 12, 12), new Leading(146, 12, 12)));
		add(getJLabel5(), new Constraints(new Leading(12, 12, 12), new Leading(180, 12, 12)));
		add(getJLabel6(), new Constraints(new Leading(12, 12, 12), new Leading(214, 12, 12)));
		add(getJPasswordField0(), new Constraints(new Leading(94, 12, 12), new Leading(212, 12, 12)));
		add(getJButton0(), new Constraints(new Leading(14, 10, 10), new Leading(248, 12, 12)));
		add(getJTextField2(), new Constraints(new Leading(94, 108, 12, 12), new Leading(178, 12, 12)));
		add(getJTextField1(), new Constraints(new Leading(94, 108, 12, 12), new Leading(144, 12, 12)));
		add(getJTextField0(), new Constraints(new Leading(94, 108, 12, 12), new Leading(110, 12, 12)));
		add(getJLabel7(), new Constraints(new Leading(359, 10, 10), new Leading(112, 12, 12)));
		add(getJLabel9(), new Constraints(new Leading(359, 12, 12), new Leading(180, 12, 12)));
		add(getJLabel8(), new Constraints(new Leading(359, 12, 12), new Leading(146, 12, 12)));
		add(getJLabel10(), new Constraints(new Leading(359, 12, 12), new Leading(214, 12, 12)));
		add(getJTextField3(), new Constraints(new Leading(463, 106, 10, 10), new Leading(110, 12, 12)));
		add(getJTextField4(), new Constraints(new Leading(464, 104, 12, 12), new Leading(142, 12, 12)));
		add(getJTextField5(), new Constraints(new Leading(465, 102, 12, 12), new Leading(176, 12, 12)));
		add(getJTextField6(), new Constraints(new Leading(465, 102, 12, 12), new Leading(214, 12, 12)));
		add(getJButton1(), new Constraints(new Leading(361, 10, 10), new Leading(248, 12, 12)));
		setSize(587, 344);
	}

	private JInternalFrame getJInternalFrame0() {
		if (jInternalFrame0 == null) {
			jInternalFrame0 = new JInternalFrame();
			jInternalFrame0.setVisible(true);
			jInternalFrame0.setLayout(new GroupLayout());
		}
		return jInternalFrame0;
	}

	private JTextField getJTextField3() {
		if (jTextField3 == null) {
			jTextField3 = new JTextField();
		}
		return jTextField3;
	}

	private JTextField getJTextField6() {
		if (jTextField6 == null) {
			jTextField6 = new JTextField();
		}
		return jTextField6;
	}

	private JTextField getJTextField5() {
		if (jTextField5 == null) {
			jTextField5 = new JTextField();
		}
		return jTextField5;
	}

	private JTextField getJTextField4() {
		if (jTextField4 == null) {
			jTextField4 = new JTextField();
		}
		return jTextField4;
	}

	private JLabel getJLabel10() {
		if (jLabel10 == null) {
			jLabel10 = new JLabel();
			jLabel10.setText("Nova Password:");
		}
		return jLabel10;
	}

	private JLabel getJLabel9() {
		if (jLabel9 == null) {
			jLabel9 = new JLabel();
			jLabel9.setText("Email:");
		}
		return jLabel9;
	}

	private JLabel getJLabel8() {
		if (jLabel8 == null) {
			jLabel8 = new JLabel();
			jLabel8.setText("Nick:");
		}
		return jLabel8;
	}

	private JLabel getJLabel7() {
		if (jLabel7 == null) {
			jLabel7 = new JLabel();
			jLabel7.setText("Nome:");
		}
		return jLabel7;
	}

	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("Alterar");
		}
		return jButton1;
	}

	private JButton getJButton0() {
		if (jButton0 == null) {
			jButton0 = new JButton();
			jButton0.addActionListener(this);
			jButton0.setText("Enviar");
		}
		return jButton0;
	}

	private JPasswordField getJPasswordField0() {
		if (jPasswordField0 == null) {
			jPasswordField0 = new JPasswordField();
			jPasswordField0.setText("jPasswordField0");
			jPasswordField0.setEchoChar('?');
		}
		return jPasswordField0;
	}

	private JTextField getJTextField2() {
		if (jTextField2 == null) {
			jTextField2 = new JTextField();
		}
		return jTextField2;
	}

	private JTextField getJTextField0() {
		if (jTextField0 == null) {
			jTextField0 = new JTextField();
		}
		return jTextField0;
	}

	private JTextField getJTextField1() {
		if (jTextField1 == null) {
			jTextField1 = new JTextField();
		}
		return jTextField1;
	}

	private JLabel getJLabel6() {
		if (jLabel6 == null) {
			jLabel6 = new JLabel();
			jLabel6.setText("Password:");
		}
		return jLabel6;
	}

	private JLabel getJLabel5() {
		if (jLabel5 == null) {
			jLabel5 = new JLabel();
			jLabel5.setText("Email:");
		}
		return jLabel5;
	}

	private JLabel getJLabel4() {
		if (jLabel4 == null) {
			jLabel4 = new JLabel();
			jLabel4.setText("Nick:");
		}
		return jLabel4;
	}

	private JLabel getJLabel3() {
		if (jLabel3 == null) {
			jLabel3 = new JLabel();
			jLabel3.setText("Nome:");
		}
		return jLabel3;
	}

	private JLabel getJLabel1() {
		if (jLabel1 == null) {
			jLabel1 = new JLabel();
			jLabel1.setText("Inserir");
		}
		return jLabel1;
	}

	private JLabel getJLabel2() {
		if (jLabel2 == null) {
			jLabel2 = new JLabel();
			jLabel2.setText("Alterar Password");
		}
		return jLabel2;
	}

	private JLabel getJLabel0() {
		if (jLabel0 == null) {
			jLabel0 = new JLabel();
			jLabel0.setText("Usuário");
		}
		return jLabel0;
	}

	private static void installLnF() {
		try {
			String lnfClassname = PREFERRED_LOOK_AND_FEEL;
			if (lnfClassname == null)
				lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
			UIManager.setLookAndFeel(lnfClassname);
		} catch (Exception e) {
			System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
					+ " on this platform:" + e.getMessage());
		}
	}

	/**
	 * Main entry of the class.
	 * Note: This class is only created so that you can easily preview the result at runtime.
	 * It is not expected to be managed by the designer.
	 * You can modify it as you like.
	 */
	public static void main(String[] args) {
		installLnF();
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				Usuario_tela frame = new Usuario_tela();
				frame.setDefaultCloseOperation(Usuario_tela.EXIT_ON_CLOSE);
				frame.setTitle("Usuario_tela");
				frame.getContentPane().setPreferredSize(frame.getSize());
				frame.pack();
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		});
	}

	public void actionPerformed(ActionEvent e) {
		Component component = (Component)e.getSource();
		if(component.getName().equals("jButton0")) {

			String nome_u = jTextField0.getText();
			String nick_u = jTextField1.getText();
			String email_u = jTextField2.getText();
			String pass_u = jPasswordField0.getText();
			
			Usuario usuario = new Usuario(nome_u, nick_u, email_u, pass_u);/*mantive o nome dos atributos da classe cliente*/
			AcessoUsuarioDAO dao = new AcessoUsuarioDAO();

			dao.inserir(usuario);

			JOptionPane.showMessageDialog(null,"Inserido com Sucesso!!");
		}
	} 
	
}

Obrigada!!

17 Respostas

Anime

Oi,

http://www.guj.com.br/java/231956-java-controle-de-estoque

http://mballem.wordpress.com/2011/02/21/utilizando-swing-com-banco-de-dados/

dreampeppers99

Qual a sua dúvida?

Anime

Pelo que entendi, todas… :roll:

Mariana.Vecci

Bom, acho que não me expressei (não achei nos links isso), tenho no banco de dados, uma função que insere o
usuario. Gostaria de saber se é pssível chamar essa função a partir do botão enviar da tela.

E a outra dúvida é que não sei como fica o campo do código do usuário, já que no banco ele é serial, não sei se fiz certo no java,
mas não o mencionei em momento algum.

Acho que consegui ser mais clara agora.

beijokas

drsmachado

Sim. com CallableStatement.

Mariana.Vecci

Obrigada! Irei ver e tentar aplicar, mas antes to com o problema da chave primaria de auto incremento do banco.

Este é o erro que mostra:

[color=red]ERRO: coluna “cod_u” é do tipo integer mas expressão é do tipo character varying
Dica: Você precisará reescrever ou converter a expressão.[/color]

drsmachado

Fica como Integer, a princípio.

Mariana.Vecci
Sim, mas no banco quero que seja auto incremento, justamente pra evitar de digitar mais um campo, mas no dao e na classe eu ignorei o campo:
package sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Usuario;

public class AcessoUsuarioDAO implements UsuarioDAO{

	public void inserir(Usuario u) throws AcessoUsuarioException
	{
		Connection conexao = null;
		PreparedStatement comando = null;
		try
		{
			conexao = Conexao.getConexao();
			String sql = "INSERT INTO Usuario VALUES (?, ?, ?, ?)";
			comando = conexao.prepareStatement(sql);
			comando.setString(1, u.getNome_u());
			comando.setString(2, u.getNick_u());
			comando.setString(3, u.getEmail_u());
			comando.setString(4, u.getPass_u());
			comando.executeUpdate();
			System.out.println(sql);

		}
		catch(SQLException e)
		{
			throw new AcessoUsuarioException("erro de inserção de Usuario", e);
		}
		finally
		{
			if(conexao != null)
			{
				try
				{
					conexao.close();
					comando.close();
				}
				catch(SQLException e2)
				{
				}
			}
		}
	}
}
package model;

public class Usuario {
	  private String nome_u;
	  private String nick_u; 
	  private String email_u; 
	  private String pass_u;
	  
	public Usuario(String nome_u, String nick_u, String email_u, String pass_u) {
		super();
		this.nome_u = nome_u;
		this.nick_u = nick_u;
		this.email_u = email_u;
		this.pass_u = pass_u;
	}
	
	public String getNome_u() {
		return nome_u;
	}
	public void setNome_u(String nome_u) {
		this.nome_u = nome_u;
	}
	public String getNick_u() {
		return nick_u;
	}
	public void setNick_u(String nick_u) {
		this.nick_u = nick_u;
	}
	public String getEmail_u() {
		return email_u;
	}
	public void setEmail_u(String email_u) {
		this.email_u = email_u;
	}
	public String getPass_u() {
		return pass_u;
	}
	public void setPass_u(String pass_u) {
		this.pass_u = pass_u;
	}
}
drsmachado

Lembra do que eu disse no outro tópico?
Você está ignorando uma coluna, logo, deverá dizer ao banco de dados quais colunas está valorando.

duduribeiro

Tenta assim,

[]'s

Mariana.Vecci

duduribeiro :

Funcionou!
Obrigada!

duduribeiro

por nada :).
qndo puder coloca no título do tópico [RESOLVIDO].
[]'s

Anime

Oi Mariana.Vecci,

Nos links que passei tem isso sim, quando estiver pesquisando procure entender os códigos, na maioria das vezes será necessário fazer alguma adaptação.

Bons estudos! :wink:

Mariana.Vecci

Anime: Desculpe! não devo ter olhado direito.

Bom, agora voltando ao assunto principal do tópico, o drsmachado me falou sobre o CallableStatement, para que eu possa utilizar uma função sql criada no banco,
no caso: “inserir_usuario (nome_u, nick_u, email_u, pass_u)”.

Dei uma pesquisada e achei um exemplo, quero adapta-lo para meu código, fiz assim:

String nome_u; String nick_u; String email_u; String pass_u; Connection conexao; CallableStatement cstmt; ResultSet rs; ... cstmt = conexao.prepareCall("CALL inserir_usuario(?,?,?,?)"); // Create a CallableStatement object cstmt.setString (1, "DISPLAY THREAD(*)"); // Set input parameter (DB2 command) cstmt.registerOutParameter (2, Types.INTEGER); // Register output parameters cstmt.registerOutParameter (3, Types.INTEGER); cstmt.registerOutParameter (4, Types.INTEGER); cstmt.registerOutParameter (5, Types.VARCHAR); cstmt.executeUpdate(); // Call the stored procedure nome_u = cstmt.getString(2); // Get the output parameter values nick_u = cstmt.getString(3); email_u = cstmt.getString(4); pass_u = cstmt.getString(5); cstmt.close();

Mas não sei se arrumei certo, e por fim, não sei aonde deveria colocar isso, em alguma classe já criada?
Obrigada pela paciência!
beijoka!

drsmachado

Então, sabe o Statement ou PreparedStatement que faz as ações com o banco de dados, geralmente colocados no DAO?
É ali que ele deve ser colocado

Mariana.Vecci

drsmachado: Sei sim! Já utilizei eles no programa, tentei dar mais uma arrumada seguindo o outro inserir.

Obrigadaa!

Mariana.Vecci

Gente, tentei testar a função no main, mas não está dando certo, acusa este erro:

[color=red]Exception in thread “main” java.lang.NullPointerException
at sql.AcessoUsuarioDAO.inserir_funcao_SQL(AcessoUsuarioDAO.java:63)
at sql.TesteUsuarioDAO.main(TesteUsuarioDAO.java:17)[/color]

Obrigada!

Criado 8 de junho de 2011
Ultima resposta 9 de jun. de 2011
Respostas 17
Participantes 5