Boa tarde,
Estou acompanhando uma aula free no youtube e na parte para criar uma tela de login usando Netbeans 8.2 (JavaSE 8) e MySQL com Workbench 8.0.26 depois de eu fazer tudo igual me aparece o erro de que o database não foi selecionado:
java.sql.SQLException: No database selected
Verifiquei várias vezes possíveis erros de sintaxe mas não consegui descobrir o problema:
Codigo Java:
package br.com.xinfo.telas;
import java.sql.*;
import br.com.xinfo.dal.ModuloConexao;
import javax.swing.*;
public class TelaLogin extends javax.swing.JFrame {
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
public void logar() {
//pesquisar usuario e senha no sql
String sql = "select usuario, senha from tbusuarios where login=? and senha=?";
try {
//as linhas abaixo preparam a consulta ao db em funcao do que
//foi digitado nas caixas de texto. O ? é substituido pelo
//conteudo das variaveis
pst = conexao.prepareStatement(sql);
pst.setString(1, txtUsuario.getText());
pst.setString(2, txtSenha.getText());
//a linha abaixo executa a query(consulta)
rs = pst.executeQuery();
//se existir usuario e senha correspondente
if (rs.next()) {
TelaPrincipal principal = new TelaPrincipal();
principal.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "usuario e/ou senha invalido(s)");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public TelaLogin() {
initComponents();
conexao = ModuloConexao.conector();
//a linha abaixo serve de apoio ao status da conexao
//System.out.println(conexao);
if (conexao != null) {
//lblStatus.setText("Conectado");
lblStatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/xinfo/icones/db_conec.png")));
} else {
//lblStatus.setText("Desconectado");
lblStatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/xinfo/icones/db_desc.png")));
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
btnLogin = new javax.swing.JButton();
txtSenha = new javax.swing.JPasswordField();
lblStatus = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("XInfo System - Login");
setResizable(false);
jLabel1.setText("Usuário");
jLabel2.setText("Senha");
txtUsuario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtUsuarioActionPerformed(evt);
}
});
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
lblStatus.setText("Status");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
.addComponent(lblStatus))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSenha)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnLogin, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap(121, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLogin)
.addComponent(lblStatus))
.addContainerGap(58, Short.MAX_VALUE))
);
setSize(new java.awt.Dimension(495, 271));
setLocationRelativeTo(null);
}// </editor-fold>
private void txtUsuarioActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// chamando o metodo logar
logar();
}
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(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaLogin().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lblStatus;
private javax.swing.JPasswordField txtSenha;
private javax.swing.JTextField txtUsuario;
// End of variables declaration
}
No MySQL realmente esta como tbusuarios e está conectado no database corretamente. Mas na hora de validar o login e a senha ele informa esse erro. Pela mensagem, é como se o database não estivesse selecionado, mas ele está conectado e é o único database disponível no workbench, então eu não consigo entender o motivo do erro.
Eu copiei e coloei do workbench a expressao correta dbusuarios e colei pra ter certeza de que não fiz nada de errado mas ele persiste na mensagem de que o db não foi selecionado.
String sql = "select * from tbusuarios where login= ? and senha= ?";
A aplicação está marcando como conectado ao banco de dados e mesmo assim, eu não consegui entender o porque desta mensagem.
Se alguém puder me ajudar, eu agradeço muito.
