Advertisement
Guest User

Untitled

a guest
Sep 11th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. package br.com.paulosalvatore.conexao;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.util.List;
  8.  
  9. /**
  10. *
  11. * @author PauloSalvatore
  12. */
  13. public class Conectar {
  14. private static Connection conexao = null;
  15. private static PreparedStatement preparedStatement = null;
  16. private static ResultSet resultSet = null;
  17.  
  18. private static final String HOST = "localhost";
  19. private static final String PORTA = "3306";
  20. private static final String BANCO_DADOS = "sistema_bancario";
  21. private static final String USUARIO = "root";
  22. private static final String SENHA = "";
  23.  
  24. public static Connection iniciarConexao() {
  25. java.sql.Connection conexao = null;
  26. String driver = "com.mysql.jdbc.Driver";
  27.  
  28. String url = "jdbc:mysql://"
  29. + HOST
  30. + ":"
  31. + PORTA
  32. + "/"
  33. + BANCO_DADOS;
  34.  
  35. try {
  36. Class.forName(driver);
  37. conexao = DriverManager.getConnection(url, USUARIO, SENHA);
  38. return conexao;
  39. }
  40. catch (Exception e) {
  41. System.out.println(e);
  42. return null;
  43. }
  44. }
  45.  
  46. public static ResultSet buscarRegistro(String tabela, List<String> campos, List<String> valores) {
  47. return buscarRegistro(tabela, campos, valores, "AND");
  48. }
  49.  
  50. public static ResultSet buscarRegistro(String tabela, List<String> campos, List<String> valores, String uniaoWhere) {
  51. String sql = "SELECT * FROM " + tabela + " WHERE ";
  52.  
  53. for (int i = 0; i < campos.size(); i++) {
  54. String campo = campos.get(i);
  55. String valor = valores.get(i);
  56.  
  57. sql += campo + " LIKE '" + valor + "'";
  58.  
  59. if (i < campos.size() - 1)
  60. sql += " " + uniaoWhere + " ";
  61. }
  62.  
  63. System.out.println(sql);
  64.  
  65. conexao = Conectar.iniciarConexao();
  66.  
  67. resultSet = null;
  68.  
  69. try {
  70. preparedStatement = conexao.prepareStatement(sql);
  71.  
  72. resultSet = preparedStatement.executeQuery();
  73. }
  74. catch (Exception e) {
  75. System.out.println(e);
  76. }
  77.  
  78. return resultSet;
  79. }
  80.  
  81. public static int pegarQuantidadeResultados(ResultSet resultSet) {
  82. int quantidadeResultados = 0;
  83.  
  84. try {
  85. if (resultSet.last()) {
  86. quantidadeResultados = resultSet.getRow();
  87. resultSet.beforeFirst();
  88. }
  89. }
  90. catch (Exception e) {
  91. System.out.println(e);
  92. }
  93.  
  94. return quantidadeResultados;
  95. }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement