Advertisement
Guest User

Untitled

a guest
May 21st, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. package com.jdbc.mysql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6.  
  7. public class ConexaoDB {
  8. //Atributos
  9. private Connection connection = null; //Conexão
  10. private Statement statement = null; //Envia as consultas ao BD
  11. private ResultSet resultset = null; //Salva os resultados das consultas
  12.  
  13. //Conectar
  14. public void conectar(){
  15. String servidor = "jdbc:mysql://localhost:3307/query_db";
  16. String usuario = "davi";
  17. String senha = "davi7412";
  18. String driver = "com.mysql.jdbc.Driver";
  19. try {
  20.  
  21. } catch (Exception e){
  22. System.out.print("Erro: "+e.getMessage());
  23. }
  24. }
  25.  
  26. //Testar se a conexão tá conectado
  27. public boolean estaConectado(){
  28. if(this.connection != null){
  29. return true;
  30. } else {
  31. return false;
  32. }
  33. }
  34.  
  35. //Desconectar Banco de Dados
  36. public void desconectar(){
  37. try{
  38. this.connection.close();
  39. }catch(Exception e){
  40. System.out.println("Erro: "+e.getMessage());
  41. }
  42. }
  43.  
  44. //Buscar Perguntas
  45. public void obterPergunta(){
  46. try{
  47. //Testar se está conectado e se não, conectar
  48. if(estaConectado() == false)
  49. conectar();
  50. //Comando SQL
  51. String query = "SELECT txt_pergunta, id_perguntas FROM perguntas ORDER BY RAND() LIMIT 1";
  52. this.resultset = this.statement.executeQuery(query);
  53. this.statement = this.connection.createStatement();
  54. }catch(Exception e){
  55. System.out.println("Erro: "+e.getMessage());
  56. } finally {
  57. desconectar();
  58. }
  59. }
  60.  
  61. //Busca com retorno
  62. public void comandoComRetorno(){
  63. try{
  64. //Comando SQL
  65. String query = "";
  66. this.resultset = this.statement.executeQuery(query);
  67. this.statement = this.connection.createStatement();
  68. }catch(Exception e){
  69. System.out.println("Erro: "+e.getMessage());
  70. } finally {
  71. desconectar();
  72. }
  73. }
  74.  
  75. //Comando de alteração - inserir, editar, remover
  76. public void comandoSemRetorno(){
  77. try{
  78. //Comando SQL
  79. String query = "";
  80. this.statement.executeUpdate(query);
  81. }catch(Exception e){
  82. System.out.println("Erro: "+e.getMessage());
  83. } finally {
  84. desconectar();
  85. }
  86. }
  87.  
  88. /*
  89. //Buscando várias linhas
  90. while(this.resultset.next()){
  91. System.out.println("ID: "+ this.resultset.getString("id")...
  92. }
  93.  
  94. */
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement