公共(public)类(class) BancoDeDados {
static String url = "jdbc:mysql://localhost:3306/Estoque";
static String pass = "admin";
static String user = "admin";
static Connection conexao = null;
public static boolean conecta() throws ClassNotFoundException {
try {
Class.forName("mysql.Driver");
conexao = DriverManager.getConnection(url, user, pass);
//System.out.println("Conectado.");
JOptionPane.showMessageDialog(null, "Conectado com Sucesso!");
return true;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Usuário e/ou senha estão incorretos!");
//System.out.println("Usuário e/ou senha estão errados.");
return false;
}
}
公共(public)类 TelaPrincipal 扩展 JFrame {
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
private JPanel contentPane;
private JTextField textLogin;
private JPasswordField textSenha;
public void logar(){
String sql = "Select *from Login WHERE Usuario = ? and senha = ?";
try{
pst = conexao.prepareStatement(sql);
pst.setString(1, textLogin.getText());
pst.setString(2, textSenha.getText());
rs = pst.executeQuery();
if(rs.next()){
TelaOpcoes telaopcoes = new TelaOpcoes();
telaopcoes.setVisible(true);
dispose();
}
else{
JOptionPane.showMessageDialog(null, "Usuário e Senha Inválidos");
}
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaPrincipal frame = new TelaPrincipal();
frame.setVisible(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaPrincipal() throws ClassNotFoundException {
conexao = BancoDeDados.conecta();
this.setLocationRelativeTo(null);
它在倒数第二行“CONEXAO = BANCODEDADOS.CONECTA(); ”上执行错误,表示“类型不匹配:无法从 boolean 值转换为连接” 有人可以帮我吗?谢谢!
最佳答案
CONEXAO = BANCODEDADOS.CONECTA();
这里CONEXAO是一个连接变量
但是方法 BANCODEDADOS.CONECTA();返回一个 boolean 值。
所以改变变量CONEXAO的类型
或者创建一个新的变量 boolean 类型来存储结果 boolean conexao = BancoDeDados.conecta();
关于Java MySQL和JFrame连接 "Cannot convert from boolean to connection",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30930084/