为什么无法在Java中连接到MySQL驱动程序数据库?

问题描述 投票:0回答:2

您好,我的连接代码可在其他类中使用,但在这里说:线程“ 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 mysql-connector
2个回答
1
投票

尝试如下运行:

java -cp path-to-jdbc-driver-jar your-java-class

我希望您已经知道-classpath-cp选项。如果不是,请阅读this文档。


-1
投票

您是否安装MySQL jdbc驱动程序验证您的数据库连接数据库->新连接->测试连接

© www.soinside.com 2019 - 2024. All rights reserved.