您好,我的连接代码可在其他类中使用,但在这里说:线程“ AWT-EventQueue-0”中的异常java.lang.IllegalStateException:在类路径中找不到驱动程序!
我的代码如下:
tfield2.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(tfield2.getText().equals("REC1U")) {
String url = "jdbc:mysql://localhost:3306/redpraire";
String username = "username";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
Statement stmt = connection.createStatement();
try {
ResultSet rs = stmt.executeQuery("SELECT * FROM product");
while(rs.next()) {
// some code here
}
rs.next();
} finally {
stmt.close();
}
} catch (SQLException ex) {
throw new IllegalStateException("Cannot connect the database!", ex);
}
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("Cannot find the driver in the classpath!", ex);
}
} else {
}
} else if(e.getKeyCode() == 121) {
frame.setVisible(false);
frame.dispose();
new QueryMenu();
}
}
});
我尝试了不同的方法来更改它,但是没有任何效果。在单独的类中,此连接可以正常工作...我只是没有主意。有什么帮助吗?
您是否安装MySQL jdbc驱动程序验证您的数据库连接数据库->新连接->测试连接