简体   繁体   中英

connecting java to Mysql using Mysql-connector/j

I use netbeans 6.9 IDE and its features to connect my java class to Mysql database. as you know, Mysql-connector driver is embedded in netbeans. I make new connection to Mysql database using Mysql(connector/j) driver, and every thing is okay, it displays all databases in Mysql and all tables in these databases, but when I create my java class to test the connetion and start manipulation, ClassNotFoundException is thrown when I call Class.forName("com.mysql.jdbc.Driver").newInstance(); ie. there is no driver ? why i got that exception ? the same happened when I connect to derby embedded db? can you help? here my test class

public static void main(String[] args) {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            System.out.println("driver true");
            con = DriverManager.getConnection("jdbc:mysql:///test",
                    "root", "123456");
            if (!con.isClosed()) {
                System.out.println("Successfully connected to "
                        + "MySQL server using TCP/IP...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Exception: " + e.getMessage());
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
            }
        }
    }

您必须将mysql连接器.jar文件(库+添加库+ Mysql JDBC驱动程序)添加到项目中。

在左侧,右键单击“ ”->“ 添加库... ”-选择->“ MySQL JDBC驱动程序 ”,然后重建项目。

您需要将MySQL Connector / J库添加到项目的类路径中,否则Java将无法找到驱动程序类文件。

The answer is with your question. Driver is with your netbeans IDE and not with your java project. Add the required dirver (Jar file) to the project and run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM