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) {
}
}
}
解决方案
You have to add the mysql connector .jar file (Libraries + Add Library + Mysql JDBC Driver) to your project.