Last active
August 29, 2015 14:24
-
-
Save fkenjikamei/087e2b8652ab2099f11a to your computer and use it in GitHub Desktop.
Classes em Java para Conexão com o Banco de Dados MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
public class ConexaoMySQL implements IConexao { | |
private String usuario; | |
private String senha; | |
private static Connection conexao; | |
public ConexaoMySQL(String usuario, String senha) { | |
this.usuario = usuario; | |
this.senha = senha; | |
} | |
@Override | |
public Connection getConexao() { | |
//Está errado, porque isso deveria estar em uma classe da camada de negócio | |
if(this.usuario == "" || this.senha == "" || this.usuario == null || this.senha == null) { | |
return null; | |
} | |
try { | |
if(conexao == null) { | |
conexao = DriverManager.getConnection("jdbc:mysql://localhost/poo", this.usuario, this.senha); | |
} | |
return conexao; | |
} catch (SQLException e) { | |
throw new RuntimeException("Erro na conexão: "+e.getMessage()); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import org.junit.Test; | |
import junit.framework.TestCase; | |
public class ConexaoTest extends TestCase { | |
@Test | |
public void testDeveRetornarConexaoValida() throws Exception { | |
IConexao conexao = new ConexaoMySQL("admin","admin"); | |
assertNotNull(conexao.getConexao()); | |
} | |
@Test | |
public void testNaoDeveriaConectarSeUsuarioOuSenhaVazios() throws Exception { | |
IConexao conexao = new ConexaoMySQL("",""); | |
assertNull(conexao.getConexao()); | |
} | |
@Test | |
public void testNaoDeveriaConectarSeUsuarioOuSenhaNulos() throws Exception { | |
IConexao conexao = new ConexaoMySQL(null, null); | |
assertNull(conexao.getConexao()); | |
} | |
@Test | |
public void testNaoDeveriaConectarSeUsuarioVazioESenhaValida() throws Exception { | |
IConexao conexao = new ConexaoMySQL("", "admin"); | |
assertNull(conexao.getConexao()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
public interface IConexao { | |
Connection getConexao(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment