package View;
import util.Encryptor;
import model.DatabaseProperties;
import Ferramentas.Constantes;
import Ferramentas.ReadPropriedadesConnectionDatabase;
import Ferramentas.Tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Zeron
*/
public class Gerador extends javax.swing.JFrame {
private ReadPropriedadesConnectionDatabase readableProperties;
private DatabaseProperties databaseProperties;
private Encryptor encriptor;
private Properties prop;
private Scanner scanner;
/**
* Creates new form TesteCone
*/
public Gerador() {
initComponents();
encriptor = new Encryptor();
readableProperties = new ReadPropriedadesConnectionDatabase();
databaseProperties = new DatabaseProperties();
prop = new Properties();
scanner = new Scanner(System.in);
setLocationRelativeTo(null); // abrir no meio o form
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
generateFilePropertiesConnection();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro!!!");
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
databaseProperties = readableProperties.getPropriedadesConnectionDatabase();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Erro!wqeqwe!!");
}
System.out.println(databaseProperties);
jtfBancoDados.setText(databaseProperties.getBanco());
jtfIP.setText(databaseProperties.getIp());
jtfUsuario.setText(databaseProperties.getUsuario());
jtfSenha.setText(databaseProperties.getSenha());
}
private void generateFilePropertiesConnection() throws Exception {
String prefix, databaseSelection;
File file = new File(Constantes.PATH_DEFAULT.concat("/").concat(Constantes.FILE_NAME));
FileOutputStream out;
databaseSelection = "1";
String banco = jtfBancoDados.getText();
String ip = jtfIP.getText();
String usuario = jtfUsuario.getText();
String senha = jtfSenha.getText();
prefix = Tools.getPrefix(databaseSelection);
prop.setProperty("configuration.jdbc.dbselection", databaseSelection);
prop.setProperty(prefix.concat(".").concat("database"), banco);
prop.setProperty(prefix.concat(".").concat("driver"), Tools.getDriver(databaseSelection));
prop.setProperty(prefix.concat(".").concat("ip"), ip);
prop.setProperty(prefix.concat(".").concat("porta"), Tools.getPort(databaseSelection));
prop.setProperty(prefix.concat(".").concat("usuario"), usuario);
prop.setProperty(prefix.concat(".").concat("senha"), senha);
try {
out = new FileOutputStream(file);
prop.store(out, "Arquivo de configuração de propriedades para conexão JDBC.");
JOptionPane.showMessageDialog(null, "Arquivo criado com sucesso em: ".concat(file.getAbsolutePath()));
} catch (IOException ex) {
throw new Exception(ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Gerador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gerador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gerador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gerador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Gerador().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField jtfBancoDados;
private javax.swing.JTextField jtfIP;
private javax.swing.JPasswordField jtfSenha;
private javax.swing.JTextField jtfUsuario;
private keeptoo.KGradientPanel kGradientPanel2;
// End of variables declaration
}
esse é o gerador, ele está gravando e lendo, tranquilamente. Porque coloquei um jbutton, pra puxar as informações além do console pra ver se estava lendo corretamente.
Agora, na classe de conexão não funciona. Veja:
package conexoes;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import Ferramentas.ReadPropriedadesConnectionDatabase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import model.DatabaseProperties;
/**
*
* @author Zeron
*/
public class ConexaoMySql {
private ReadPropriedadesConnectionDatabase lerPropriedade;
private DatabaseProperties propriedadeBD;
private boolean status = false;
private String mensagem = ""; //variavel que vai informar o status da conexao
private Connection con = null; //variavel para conexao
private Statement statement;
private ResultSet resultSet;
private String servidor = propriedadeBD.getIp();//local
private String nomeDoBanco = propriedadeBD.getBanco(); //banco de dados do rogério
private String usuario = propriedadeBD.getUsuario();
private String senha = propriedadeBD.getSenha();
public ConexaoMySql() {
readFileProperties();
}
public ConexaoMySql(String pServidor, String pNomeDoBanco, String pUsuario, String pSenha) {
this.servidor = pServidor;
this.nomeDoBanco = pNomeDoBanco;
this.usuario = pUsuario;
this.senha = pSenha;
}
public void readFileProperties() {
try {
propriedadeBD = lerPropriedade.getPropriedadesConnectionDatabase();
} catch (Exception ex) {
System.out.println(ex.getCause());
}
}
/**
* Abre uma conexao com o banco
*
* @return Connection
*/
public Connection conectar() {
try {
//Driver do PostgreSQL
Class.forName("com.mysql.jdbc.Driver").newInstance();
//local do banco, nome do banco, usuario e senha
String url = "jdbc:mysql://" + servidor + "/" + nomeDoBanco;
this.setCon((Connection) DriverManager.getConnection(url, usuario, senha));
//se ocorrer tudo bem, ou seja, se conectar a linha a segui é executada
this.status = true;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return this.getCon();
}
/**
* Executa consultas SQL
*
* @param pSQL
* @return int
*/
public boolean executarSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.setResultSet(getStatement().executeQuery(pSQL));
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
return true;
}
public boolean executarUpdateDeleteSQL(String pSQL) {
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
getStatement().executeUpdate(pSQL);
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* Executa insert SQL
*
* @param pSQL
* @return boolean
*/
public int insertSQL(String pSQL) {
int status = 0;
try {
//createStatement de con para criar o Statement
this.setStatement(getCon().createStatement());
// Definido o Statement, executamos a query no banco de dados
this.getStatement().executeUpdate(pSQL);
//consulta o ultimo id inserido
this.setResultSet(this.getStatement().executeQuery("SELECT last_insert_id();"));
//recupera o ultimo id inserido
while (this.resultSet.next()) {
status = this.resultSet.getInt(1);
}
//retorna o ultimo id inserido
return status;
} catch (SQLException ex) {
ex.printStackTrace();
return status;
}
}
/**
* encerra a conexão corrente
*
* @return boolean
*/
public boolean fecharConexao() {
try {
if ((this.getResultSet() != null) && (this.statement != null)) {
this.getResultSet().close();
this.statement.close();
}
this.getCon().close();
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return false;
}
/**
* @return the status
*/
public boolean isStatus() {
return this.status;
}
/**
* @return the mensagem
*/
public String getMensagem() {
return mensagem;
}
/**
* @return the statement
*/
public Statement getStatement() {
return statement;
}
/**
* @return the resultSet
*/
public ResultSet getResultSet() {
return resultSet;
}
/**
* @param mensagem the mensagem to set
*/
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
/**
* @return the con
*/
public Connection getCon() {
return con;
}
/**
* @param con the con to set
*/
public void setCon(Connection con) {
this.con = con;
}
/**
* @param statement the statement to set
*/
public void setStatement(Statement statement) {
this.statement = statement;
}
/**
* @param resultSet the resultSet to set
*/
public void setResultSet(ResultSet resultSet) {
this.resultSet = resultSet;
}
/**
* @return the servidor
*/
public String getServidor() {
return servidor;
}
/**
* @param servidor the servidor to set
*/
public void setServidor(String servidor) {
this.servidor = servidor;
}
/**
* @return the nomeDoBanco
*/
public String getNomeDoBanco() {
return nomeDoBanco;
}
/**
* @param nomeDoBanco the nomeDoBanco to set
*/
public void setNomeDoBanco(String nomeDoBanco) {
this.nomeDoBanco = nomeDoBanco;
}
/**
* @return the usuario
*/
public String getUsuario() {
return usuario;
}
/**
* @param usuario the usuario to set
*/
public void setUsuario(String usuario) {
this.usuario = usuario;
}
/**
* @return the senha
*/
public String getSenha() {
return senha;
}
/**
* @param senha the senha to set
*/
public void setSenha(String senha) {
this.senha = senha;
}
}