Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.");
- }
- }
- }
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement