我正在尝试连接到数据库。早先它工作正常。但是现在有些罐子已被删除或者我不知道的东西(红十字会出现在他们身上)。但是我再次下载了所有的jar(mysql-connector,commons-io-2.4),我仍然在Class.forName(“com.mysql.jdbc.Driver”)中得到classnotfound异常; 这是我的代码
package abc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
//step3 create the statement object
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query");
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}
这是错误
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at deiniteguide.JDBC_example.main(JDBC_example.java:24)
我尝试过使用try catch也不适合我。
答案 0 :(得分:1)
如果您使用的是netbeans,则可以转到项目中的库文件夹。右键单击并添加库并选择mysql驱动程序。抱歉由于声誉较低而无法发表评论,如果您可以发布您收到的错误消息会更容易。还可以在程序中使用try catch,以便更容易找到错误。您的代码可以是这样的:
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("Class not found" +e);
//step2 create the connection object
try{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
}catch(Exception es){
System.out.println("connection couldn't be made "+es);
}
//step3 create the statement object
try{
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query"); }
catch(Exception er){
System.out.println("Query wasnot executed "+er);
}
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}