Comparação de Código com Access

0 respostas
danielsantunes

To com dificuldades em comparar os códigos já existentes no meu BD, com o digitado na interface do meu programa, pra não haver duplicaçãode código!!!

Meu codigo de conexão com o banco é esse:

import java.sql.*;
import javax.swing.*;

public class Conexao
{
	final private String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
	// voces verão ainda como efetuar conexão com diversos bancos
	final private String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents and Settings/Usuario/Meus documentos/BD NEGUINHO AUTO PEÇAS/bd1.mdb";
	final private String usuario = "";
	final private String senha = "";
	private Connection conexao;
	public Statement statement;
	public ResultSet resultset;

	public boolean conecta()
	{
		boolean result = true;
		try 
		{
			Class.forName(driver);
			conexao = DriverManager.getConnection(url, usuario, senha);
			//JOptionPane.showMessageDialog(null,"conectou");
		}
		catch(ClassNotFoundException Driver) 
		{
			JOptionPane.showMessageDialog(null,"Driver não localizado: "+Driver);
			result = false;
		}
		catch(SQLException Fonte) 
		{
			JOptionPane.showMessageDialog(null,"Deu erro na conexão "+
					"com a fonte de dados: "+Fonte);
			result = false;
		}
		return result; 
	}

	public void desconecta()
	{
		boolean result = true;
		try 
		{
			conexao.close();
			//JOptionPane.showMessageDialog(null,"Banco Fechado");
		}
		catch(SQLException fecha) 
		{
			JOptionPane.showMessageDialog(null,"Não foi possivel "+
					"fechar o banco de dados: "+fecha);
			result = false;
		}

	}

	public void executeSQL(String sql)
	{
		try 
		{
			statement = conexao.createStatement(
					ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
			resultset = statement.executeQuery(sql);
		}
		catch(SQLException sqlex) 
		{
			JOptionPane.showMessageDialog(null,"Não foi possível "+
					"executar o comando sql,"+sqlex+", o sql passado foi "+sql);
		}

	}

}

e tenho uma tela de cadastro de produtos, e é nessa tela de cadastro q eu quero fazer a comparação!

import java.awt.BorderLayout;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import java.awt.event.KeyEvent;
import java.awt.Point;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JTextField;
import javax.swing.JComboBox;
import java.awt.Font;

public class Cad_Produto extends JFrame {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JTextField tf_Cod = null;

	private JTextField tf_Desc = null;

	private JTextField tf_Un = null;

	private JTextField tf_Entrada = null;

	private JTextField tf_VlrCompra = null;

	private JTextField tf_VlrVenda = null;

	private JButton jButton_Ok = null;

	private JButton jButton_Cancel = null;

	private JButton jButton_Limpa = null;

	private JLabel jLabel_cod = null;

	private JLabel jLabel_desc = null;

	private JLabel jLabel_entrada = null;

	private JLabel jLabel_un = null;

	private JLabel jLabel_compra = null;

	private JLabel jLabel_venda = null;
	
	Conexao con_prod;

	/**
	 * This is the default constructor
	 */
	public Cad_Produto() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(544, 249);
		this.setContentPane(getJContentPane());
		this.setTitle("Cadastro de Produtos");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jLabel_venda = new JLabel();
			jLabel_venda.setBounds(new Rectangle(20, 129, 159, 24));
			jLabel_venda.setText("Valor de Venda.:");
			jLabel_venda.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_compra = new JLabel();
			jLabel_compra.setBounds(new Rectangle(20, 100, 160, 24));
			jLabel_compra.setText("Valor de Compra.:");
			jLabel_compra.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_un = new JLabel();
			jLabel_un.setBounds(new Rectangle(343, 70, 96, 24));
			jLabel_un.setText("Unidade.:");
			jLabel_un.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_entrada = new JLabel();
			jLabel_entrada.setBounds(new Rectangle(20, 71, 94, 24));
			jLabel_entrada.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_entrada.setText("Entrada.:");
			jLabel_desc = new JLabel();
			jLabel_desc.setBounds(new Rectangle(20, 40, 106, 26));
			jLabel_desc.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
			jLabel_desc.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_desc.setText("Descrição.:");
			jLabel_cod = new JLabel();
			jLabel_cod.setBounds(new Rectangle(20, 10, 81, 25));
			jLabel_cod.setFont(new Font("Dialog", Font.BOLD, 18));
			jLabel_cod.setText("Código.:");
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getTf_Cod(), null);
			jContentPane.add(getTf_Desc(), null);
			jContentPane.add(getTf_Un(), null);
			jContentPane.add(getTf_Entrada(), null);
			jContentPane.add(getTf_VlrCompra(), null);
			jContentPane.add(getTf_VlrVenda(), null);
			jContentPane.add(getJButton_Ok(), null);
			jContentPane.add(getJButton_Cancel(), null);
			jContentPane.add(getJButton_Limpa(), null);
			jContentPane.add(jLabel_cod, null);
			jContentPane.add(jLabel_desc, null);
			jContentPane.add(jLabel_entrada, null);
			jContentPane.add(jLabel_un, null);
			jContentPane.add(jLabel_compra, null);
			jContentPane.add(jLabel_venda, null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes tf_Cod	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_Cod() {
		if (tf_Cod == null) {
			tf_Cod = new JTextField();
			tf_Cod.setBounds(new Rectangle(128, 10, 112, 26));
		}
		return tf_Cod;
	}

	/**
	 * This method initializes tf_Desc	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_Desc() {
		if (tf_Desc == null) {
			tf_Desc = new JTextField();
			tf_Desc.setLocation(new Point(128, 40));
			tf_Desc.setSize(new Dimension(398, 26));
		}
		return tf_Desc;
	}

	/**
	 * This method initializes tf_Un	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_Un() {
		if (tf_Un == null) {
			tf_Un = new JTextField();
			tf_Un.setLocation(new Point(441, 70));
			tf_Un.setSize(new Dimension(85, 26));
		}
		return tf_Un;
	}

	/**
	 * This method initializes tf_Entrada	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_Entrada() {
		if (tf_Entrada == null) {
			tf_Entrada = new JTextField();
			tf_Entrada.setLocation(new Point(129, 70));
			tf_Entrada.setSize(new Dimension(149, 26));
		}
		return tf_Entrada;
	}

	/**
	 * This method initializes tf_VlrCompra	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_VlrCompra() {
		if (tf_VlrCompra == null) {
			tf_VlrCompra = new JTextField();
			tf_VlrCompra.setLocation(new Point(182, 100));
			tf_VlrCompra.setSize(new Dimension(116, 26));
		}
		return tf_VlrCompra;
	}

	/**
	 * This method initializes tf_VlrVenda	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTf_VlrVenda() {
		if (tf_VlrVenda == null) {
			tf_VlrVenda = new JTextField();
			tf_VlrVenda.setLocation(new Point(182, 129));
			tf_VlrVenda.setSize(new Dimension(116, 26));
		}
		return tf_VlrVenda;
	}

	/**
	 * This method initializes jButton_Ok	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton_Ok() {
		if (jButton_Ok == null) {
			jButton_Ok = new JButton();
			jButton_Ok.setText("Ok");
			jButton_Ok.setSize(new Dimension(131, 26));
			jButton_Ok.setLocation(new Point(347, 177));
			jButton_Ok.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if(tf_Cod.getText().equals("")||tf_Desc.getText().equals("")||tf_Entrada.getText().equals(""))
						JOptionPane.showMessageDialog(null, "Favor preencher todos dos campos!!!");
					else {
						//if(comparaCod()== false)
						//{
						insertProd();
						limpatfs();
						//}
						//else{
						//	JOptionPane.showMessageDialog(null, "Código já existe!!!");
							
						//}
					}
				}
			});
		}
		return jButton_Ok;
	}

	/**
	 * This method initializes jButton_Cancel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton_Cancel() {
		if (jButton_Cancel == null) {
			jButton_Cancel = new JButton();
			jButton_Cancel.setText("Cancelar");
			jButton_Cancel.setSize(new Dimension(131, 26));
			jButton_Cancel.setLocation(new Point(201, 177));
			jButton_Cancel.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					new Tela_Principal().show();
					setVisible(false);
				}
			});
		}
		return jButton_Cancel;
	}

	/**
	 * This method initializes jButton_Limpa	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton_Limpa() {
		if (jButton_Limpa == null) {
			jButton_Limpa = new JButton();
			jButton_Limpa.setText("Limpar");
			jButton_Limpa.setSize(new Dimension(131, 26));
			jButton_Limpa.setLocation(new Point(54, 177));
			jButton_Limpa.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					limpatfs();
				}
			});
		}
		return jButton_Limpa;
	}

	
	//INSERE OS DADOS DIGITADOS NO BANCO DE DADOS
	public void insertProd(){

		String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents and Settings/Usuario/Meus documentos/BD NEGUINHO AUTO PEÇAS/bd1.mdb";
		try
		{
//			registra o driver
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//			registra o driver, basta apenas estabelecer uma conexão
//			observe a passagem de três parâmetros
//			Primeiro: a string BD com o "endereço" do banco de dados
//			Segundo: Nome do usuário para acessar o banco, neste caso nenhum
//			Terceiro: Senha do usuário para acessar o banco, também nenhum
			Connection con = DriverManager.getConnection(url,"","");
//			Objeto para ativar a passagem de comandos SQL
			Statement p = con.createStatement();
//			Comando SQL para inserção de dados
			p.executeUpdate("INSERT INTO Tb_Produtos (Codigo,Descricao,Entrada, Unid, Vlr_Compra, Vlr_Venda)"+
					"values ('"+tf_Cod.getText()+"',"+"'"+tf_Desc.getText()+"',"+"'"+tf_Entrada.getText()+"',"+"'"+tf_Un.getText()+"',"+"'"+tf_VlrCompra.getText()+"',"+"'"+tf_VlrVenda.getText()+"')");
			//JOptionPane.showMessageDialog(null, "Dados inseridos com sucesso!!!");
//			Fecha a conexão
			con.close();
		}
//		Observação com Exception!! Pois se for outro tipo Não funciona!
		catch (Exception e)
		{
//			Caso ocorra algum problema durante a operação
			JOptionPane.showMessageDialog(null, "Problema durante a operação!!!");

		}
	}
	
	//LIMPA AS TFS DO CADASTRO DE PRODUTOS
	public void limpatfs(){
		tf_Cod.setText("");
		tf_Desc.setText("");
		tf_Un.setText("");
		tf_Entrada.setText("");
		tf_VlrCompra.setText("");
		tf_VlrVenda.setText("");
	}
	
	
	/*public boolean comparaCod(){
		
		boolean status =  false;
		try
		{
			String sql = "select * from Tb_Produtos Where Codigo like '"+
			tf_Cod.getText()+"'";
			con_prod.executeSQL(sql);
			if (con_prod.resultset.first())
			{
				status = true;
				//usu = con_usuario.resultset.getString("usuario");
				//JOptionPane.showMessageDialog(null,"Código digitado já existe!!!");
				//new Tela_Principal().show();
				//Tela_Principal.lb_nomeUsuario.setText(con_usuario.resultset.getString("usuario"));
				//dispose();
			}
			else
			{
				status = false;
				//conta++;                 
				//if (conta == 1)
				//	JOptionPane.showMessageDialog(null,"Senha Incorreta, Você só tem mais uma chance");
				//else
				//{
				//	JOptionPane.showMessageDialog(null,"De novo senha incorreta, Usuário Inabilitado para usar o Sistema\n\nO Sistema será finalizado");                         
				//	dispose();
				//}
			}

		}

		catch(SQLException erro)
		{

		}
		
		return (status);
	}*/
}

Estou desenvolvendo em Eclipse..

quem puder me ajudar ficarei grato!!

Criado 4 de janeiro de 2008
Respostas 0
Participantes 1