Enum no MySQL?

18 respostas
mysql
Luiz_Paulo_Gomes_da

Como faço para inserir um atributo do tipo enum:

Exemplo:

enum sexo { Masculino , Feminino }

no NetBens com MySQL?

18 Respostas

drsmachado

Desde quando netbeans insere no banco de dados?
Você vai mandar o cliente instalar netbeans para rodar a aplicação ou vai criar um executável java?
De qualquer forma, um enum pode ter duas formas: numérica ou literal.
A forma mais comum é como literal. Em java, literal é String. Nos bancos de dados, array de char ou varchar.
Usando jdbc puro, você pode invocar o método name() do enum para inserí-lo no banco de dados.

Luiz_Paulo_Gomes_da

vc tem algum exemplo ?

Luiz_Paulo_Gomes_da

Outra coisa quando eu falo inserir quis dizer que estou fazendo um método inserir dentro do netbens

drsmachado

Cara, entenda de uma vez, você está desenvolvendo em java, php, c, c++, asp, ruby ou o que for, nunca em netbeans. Netbeans é a ferramenta que você usa para criar seus códigos, só isso.
Como você está fazendo? Onde está teu código?

Dragoon
  • Poste o seu código?
  • Poste se houver erros, também?
Luiz_Paulo_Gomes_da

Essa é a classe

public abstract class Pessoa {
    
   public String nome;
   public Sexo sexo;
   
   public enum Sexo{   
    Masculino, Feminino;
   
    }
  
      
}

public class Cliente extends Pessoa implements ICrud
{
     
   public String endereco;
   public String cpf;
}

E esse é o método

public void Inserir()  {
    try {  
       String sqlInsert;
       sqlInsert = "INSERT INTO teste (nome,sexo,endereco,cpf) VALUES"
       + " ('" + this.nome + "','" + Sexo.valueOf("Masculino")+ "','" + this.endereco + "','" + this.cpf + "')";
       Conexao.getConexao();
       Conexao.getComandoSql(sqlInsert);       
    } 
    catch (Exception e) {
             JOptionPane.showMessageDialog(null,"Erro ao executar o comando Inserir :" +e );
    }         
}
L
  • Todos os elementos de um enum devem estar em letras Maiúsculas.

Exemplo:

public enum Sexo
{
    MASCULINO, FEMININO;
}
  • Você sempre vai inserir o valor “Masculino” na coluna Sexo?

Eu prefiro usar o método Sexo.MASCULINO.name() ou Sexo.FEMININO.name() para obter o valor do mesmo em String.

Luiz_Paulo_Gomes_da

E como eu faço esse método ?

Dragoon

é JDBC puro? tem como colocar essa classe Conexao?

Dragoon

tem como colocar essa classe Conexao?

Luiz_Paulo_Gomes_da
public class Conexao {

private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/infox";
private static final String usuario = "root";
private static final  String senha = "";
private static Connection con = null;

public static Connection getConexao() throws Exception{
    
        try {
          
         
          Class.forName(driver);
          con = DriverManager.getConnection(url,usuario,senha);
          //JOptionPane.showMessageDialog(null," Conectado ");
            return con;
        } 
        catch (SQLException e) {
             JOptionPane.showMessageDialog(null,"Erro ao conectar ao Banco : " +e );
        }
        return null;
}
 public static void getComandoSql(String sql) throws SQLException{
     try
     {
        PreparedStatement ps = con.prepareStatement(sql) ;
        ps.executeUpdate(); 
        
     } 
     catch (Exception e) {
           JOptionPane.showMessageDialog(null,"Erro de Sql : " +e );
     
    }
        
           
 }
}
Dragoon

Luiz é sim JDBC puro sem ORM, pera vou exemplificar isso no seu banco você tem como mandar a script de criação da tabela
?

Luiz_Paulo_Gomes_da

Enum Sexo

public enum Sexo
{
    MASCULINO, FEMININO;
}

Layout Tabela

CREATE TABLE `infox`.`teste2` 
(
  `nome` VARCHAR(30) NULL,
  `sexo` VARCHAR(16) NULL,
  `endereco` VARCHAR(45) NULL,
  `cpf` VARCHAR(15) NULL
);

Classe Conexão

public class Conexao 
{

	private static final String driver = "com.mysql.jdbc.Driver";
	private static final String url = "jdbc:mysql://localhost:3306/infox";
	private static final String usuario = "root";
	private static final  String senha = "";
	private static Connection con = null;

	public static Connection getConexao() throws Exception{

        try {


          Class.forName(driver);
          con = DriverManager.getConnection(url,usuario,senha);
          //JOptionPane.showMessageDialog(null," Conectado ");
            return con;
        } 
        catch (SQLException e) {
             JOptionPane.showMessageDialog(null,"Erro ao conectar ao Banco : " +e );
        }
        return null;
	}
	public static void getComandoSql(String sql) throws SQLException{
		try
		{
			PreparedStatement ps = con.prepareStatement(sql) ;
			ps.executeUpdate(); 
		} 
		catch (Exception e) {
			JOptionPane.showMessageDialog(null,"Erro de Sql : " +e );
		}
	}
}
Luiz_Paulo_Gomes_da

E para fazer os métodos com enum ?

Dragoon

Vou propor um exemplo, só aguarde um pouquinho que o Netbeans demora para instalar tudo bem?

Luiz_Paulo_Gomes_da

ok

Dragoon

##Deveria ser assim:


Observação: é um exemplo completo de um CRUD da tabela teste, observer o Script de criação da tabela no sexo enum('MASCULINO','FEMININO') NOT NULL, ou seja, a definição correta na tabela e no código.

Tabela:

CREATE TABLE `teste` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(30) NOT NULL,
  `endereco` varchar(45) NOT NULL,
  `sexo` enum('MASCULINO','FEMININO') NOT NULL,
  `cpf` varchar(15) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Enum

public enum Sexo
{
    MASCULINO, FEMININO;
}

Classe modelo: Teste

package javaapplication1.Models;
public class Teste 
{
    private int id;
    private String nome;
    private String endereco;
    private String cpf;
    private Sexo sexo;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getEndereco() {
        return endereco;
    }
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }
    public String getCpf() {
        return cpf;
    }
    public void setCpf(String cpf) {
        this.cpf = cpf;
    }
    public Sexo getSexo() {
        return sexo;
    }
    public void setSexo(Sexo sexo) {
        this.sexo = sexo;
    }     
}

Classe Conexao:

package javaapplication1.Models;
import java.sql.*;        
public class Connect
{
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/homestead";
    private static final String usuario = "root";
    private static final  String senha = "senha";
    private static java.sql.Connection con = null;
    
    public static  Connection getInstance() throws ClassNotFoundException, SQLException
    {
        if (con == null)
        {
            Class.forName(driver);
            con = DriverManager.getConnection(url,usuario,senha);                
        }
        return con;
    }    
}

Classe DaoTeste:

package javaapplication1.Models;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DaoTeste 
{
    private final Connection connection;
    public DaoTeste(Connection connection) 
    {
        this.connection = connection;
    }    
    public Teste add(Teste value) throws SQLException
    {
        String sql = "INSERT INTO teste(nome, endereco, sexo, cpf) VALUES(?,?,?,?);";
        PreparedStatement stmt = this.connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        stmt.setString(1, value.getNome());
        stmt.setString(2, value.getEndereco());
        stmt.setString(3, value.getSexo().name());
        stmt.setString(4, value.getCpf());
        stmt.executeUpdate();
        ResultSet key = stmt.getGeneratedKeys();
        if (key.next())
            value.setId(key.getInt(1));        
        return value;
    }    
    public boolean edit(Teste value) throws SQLException
    {
        String sql = "UPDATE teste SET nome=?, endereco=?, sexo=?, cpf=? where id=?";
        PreparedStatement stmt = this.connection.prepareStatement(sql);
        stmt.setString(1, value.getNome());
        stmt.setString(2, value.getEndereco());
        stmt.setString(3, value.getSexo().name());
        stmt.setString(4, value.getCpf());
        stmt.setInt(5, value.getId());
        return stmt.execute();
    }    
    public Teste find(int id) throws SQLException
    {
        Teste t = null;
        String sql = "SELECT * FROM teste where id=?";
        PreparedStatement stmt = this.connection.prepareStatement(sql);        
        stmt.setInt(1, id);
        ResultSet query = stmt.executeQuery();
        if (query.next())
        {
            t = new Teste();
            t.setId(query.getInt("id"));
            t.setNome(query.getString("nome"));
            t.setEndereco(query.getString("endereco"));
            t.setCpf(query.getString("cpf"));
            t.setSexo(Enum.valueOf(Sexo.class, query.getString("Sexo")));
        }
        return t;
    }    
    public List<Teste> all() throws SQLException
    {
        List<Teste> t = new ArrayList<>();        
        String sql = "SELECT * FROM teste ORDER BY id";
        PreparedStatement stmt = this.connection.prepareStatement(sql);                
        ResultSet query = stmt.executeQuery();
        Teste at = null;
        while (query.next())
        {
            at = new Teste();            
            at.setId(query.getInt("id"));
            at.setNome(query.getString("nome"));
            at.setEndereco(query.getString("endereco"));
            at.setCpf(query.getString("cpf"));
            at.setSexo(Enum.valueOf(Sexo.class, query.getString("Sexo")));
            t.add(at);
        }
        return t;
    }
}

Como usar:

  • Lista todos os dados:

DaoTeste daoTeste = new DaoTeste(Connect.getInstance());
   
for(Teste tr :daoTeste.all())
{
    System.out.println(tr.getNome() + " " + tr.getSexo());
}
  • Inserir dados

Teste t = new Teste();        
t.setCpf("[telefone removido]");
t.setEndereco("Endereco");
t.setNome("Nome");
t.setSexo(Sexo.FEMININO);

DaoTeste daoTeste = new DaoTeste(Connect.getInstance());
daoTeste.add(t);
  • Alterar dados

Teste t = new Teste();   
t.setId(2);
t.setCpf("[telefone removido]");
t.setEndereco("Endereco");
t.setNome("Nome");
t.setSexo(Sexo.FEMININO);

DaoTeste daoTeste = new DaoTeste(Connect.getInstance());
daoTeste.add(t);
  • Buscar por Id do registro

DaoTeste daoTeste = new DaoTeste(Connect.getInstance());
Teste t = daoTeste.find(1);
Luiz_Paulo_Gomes_da

Valeu companheiro obrigado

Criado 16 de março de 2017
Ultima resposta 16 de mar. de 2017
Respostas 18
Participantes 4