Skip to content

Instantly share code, notes, and snippets.

@DavidCabral
Created July 30, 2020 14:13
Show Gist options
  • Save DavidCabral/a351ed973a0579378a6fd5b293699f53 to your computer and use it in GitHub Desktop.
Save DavidCabral/a351ed973a0579378a6fd5b293699f53 to your computer and use it in GitHub Desktop.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
public class EscolaDAO extends GenericoDAO {
private static final String INSERT = "insert into infoescola values(?,?,?,?,?,?,?,?,?)";
public void inserirInfoEscola(String BD, ArrayList<String> niveis, String ensino) throws Exception {
Connection con = null;
PreparedStatement stm = null;
try {
int codigo = 0;
con = getConexao(BD);
createTransaction(con);
stm = con.prepareStatement(INSERT);
for (String nivel : niveis) {
codigo = cID.recuperarCodigo(BD, "curso", "id");
++codigo;
stm.setInt(1, codigo);
stm.setString(2, "");
stm.setString(3, nivel);
stm.setString(4, "");
stm.setString(5, "");
stm.setInt(6, 0);
stm.setInt(7, 0);
stm.setString(8, ensino);
stm.setInt(9, 0);
ensino = "";
stm.executeUpdate();
}
System.out.println("Dados Inseridos!!!");
commitTransaction(con);
} catch (Exception e) {
e.printStackTrace();
rollbackTransaction(con);
throw e;
} finally {
fecharRecursos(stm, con);
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Savepoint;
public class GenericoDAO {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USER = "";
private static final String PASS = "";
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Connection getConexao(String banco) throws Exception {
return DriverManager.getConnection("jdbc:mysql://localhost/"+banco, USER, PASS);
}
void commitTransaction(Connection con) throws SQLException {
if (con != null) {
con.commit();
con.setAutoCommit(true);
}
}
void rollbackTransaction(Connection con) {
if (con != null) {
try {
con.rollback();
con.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void createTransaction(Connection con) throws SQLException {
if (con != null)
con.setAutoCommit(false);
}
Savepoint createSavePoint(String name, Connection con) throws SQLException {
return con.setSavepoint(name);
}
void fecharRecursos(AutoCloseable... closes) {
for (AutoCloseable c : closes) {
try {
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment