您好,我的连接代码在其他类中工作,但在这里说: 线程“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();
}
}
});
我尝试了不同的方法来改变它,但没有任何效果...在单独的类中,此连接工作得很好... 我只是没主意了。有什么帮助吗?
最佳答案
尝试按如下方式运行它:
java -cp path-to-jdbc-driver-jar your-java-class
例如
java -cp hsqldb-2.2.9.jar org.hsqldb.util.DatabaseManagerSwing
我希望您已经了解 -classpath
或 -cp
选项。如果没有,请查看this文档。
关于java - 为什么我无法用java连接MySQL驱动数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60781577/