I am creating a system in NetBeans, using the Java language and the MySQL database. I wrote the following code to make the connection between the program and the database:
public class Conexao
{
private static final String DRIVER="com.mysql.jdbc.Driver",URL="jdbc:mysql://localhost:3306/banco_dados",USUARIO="root",SENHA="root";
public static Connection obter()
{
try
{
Class.forName(DRIVER);
return DriverManager.getConnection(URL,USUARIO,SENHA);
}
catch (ClassNotFoundException|SQLException ex)
{
JOptionPane.showMessageDialog(null,"Erro ao estabelecer conexão com o MySQL.");
}
return null;
}
public static void fechar(Connection c)
{
try
{
if(c!=null)
c.close();
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
}
}
public static void fechar(Connection c, PreparedStatement ps)
{
fechar(c);
try
{
if(ps!=null)
ps.close();
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
}
}
public static void fechar(Connection c, PreparedStatement ps, ResultSet rs)
{
fechar(c,ps);
try
{
if(rs!=null)
rs.close();
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Erro ao fechar conexão com o MySQL.");
}
}
}
For class Usuario
, I created the class UsuarioDAO
. I'll still create methods for reading, editing, and deleting.
public class UsuarioDAO
{
public static void inserir(Usuario usuario)
{
Connection c=Conexao.obter();
PreparedStatement ps=null;
try
{
ps=c.prepareStatement("insert into usuarios(nome,senha) values(?,?)");
ps.setString(1,usuario.getNome());
ps.setBytes(2,usuario.getSenha());
ps.executeUpdate();
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Erro ao inserir dados no MySQL.");
}
finally
{
Conexao.fechar(c,ps);
}
}
}
In relation to the classes above, I have the following doubts:
Is it necessary to create the Conexao
class and the DAO
classes manually or is there any functionality in NetBeans that can configure the connection of the program to the database using a form or something? >
Is it necessary to open and close the connection every time you query or change the database? Why?
Is it necessary to create three overloads of method fechar
in class Conexao
? Why?