Java MySQL CRUD Operations Code Snippets

Classified in Computers

Written on in English with a size of 3.07 KB

Conexão

try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "abc123");
} catch (ClassNotFoundException dri) {
    System.out.println("Erro ao carregar o driver" + dri.getMessage());
} catch (SQLException sql) {
    System.out.println("Erro ao conectar ao banco de dados" + sql.getMessage());
} catch (Exception e) {
    throw new RuntimeException(e);
}

Insert

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "abc123");
String sql = "insert into dados.Pessoa (nome, idade, sexo) values (?, ?, ?)";
try {
    PreparedStatement stmt = con.prepareStatement(sql);
    Pessoa p = (Pessoa) o;
    stmt.setString(1, p.getNome());
    stmt.setInt(2, p.getIdade());
    stmt.setString(3, p.getSexo());
    pessoas.add(o);
    stmt.execute();
    System.out.println("Inserido com sucesso!");
    stmt.close();
} catch (SQLException e) {
    System.out.println("Erro ao inserir");
    e.printStackTrace();
}

Delete

String sql = "delete from dados.pessoa where id = ?;";
try {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "abc123");
    PreparedStatement stmt = con.prepareStatement(sql);
    stmt.setInt(1, (int) id); // Conversão do Object para int
    if (stmt.executeUpdate() == 1) {
        System.out.println("Deletado com sucesso!");
    } else {
        System.out.println("ID não existe.");
    }
    stmt.close();
    con.close();
} catch (Exception e) {
    System.out.println("Erro ao deletar");
    e.printStackTrace();
}

Update

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "abc123");
String sql = "update dados.pessoa set nome = ?, idade = ?, sexo = ? where id = ?;";
try {
    PreparedStatement stmt = con.prepareStatement(sql);
    stmt.setString(1, p.getNome());
    stmt.setInt(2, p.getIdade());
    stmt.setString(3, p.getSexo());
    stmt.setInt(4, p.getId());
    stmt.execute();
    System.out.println("Atualizado com sucesso.");
    stmt.close();
    con.close();
} catch (SQLException ex) {
    System.out.println("Erro ao atualizar.");
    ex.printStackTrace();
}

Select

try {
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "abc123");
    String sql = "select id, nome, idade, sexo from dados.pessoa;";
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(sql);
    while (rs.next()) {
        Pessoa p = new Pessoa();
        p.setId(rs.getInt(1));
        p.setNome(rs.getString(2));
        p.setIdade(rs.getInt(3));
        p.setSexo(rs.getString(4).toUpperCase());
        pessoas.add(p);
    }
    System.out.println("Alunos obtidos com sucesso.");
    rs.close();
    st.close();
    con.close();
} catch (Exception e) {
    System.out.println("Erro ao obter os alunos: " + e.getMessage());
}

Related entries: