ClassNotFound从CentOS 7终端运行java时出现异常

时间:2015-02-13 02:00:04

标签: java linux jdbc terminal centos

当我尝试从CentOS 7终端运行下面​​的简单Java程序时,我在代码行java.lang.ClassNotFoundException: com.mysql.jdbc.Driver处出现Class.forName("com.mysql.jdbc.Driver");错误。 如何在下面的代码中解决此问题和类似错误,以便下面的简单程序可以正常运行?

这是我到目前为止所做的:

我导航到/ path / to /然后输入:

javac somepackage/TestJDBC.java
java somepackage.TestJDBC  

这导致上述错误。这个简单程序的完整代码是:

package somepackage;
//STEP 1. Import required packages
import java.sql.*;

public class TestJDBC {
 // JDBC driver name and database URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
 static final String DB_URL = "jdbc:mysql://localhost:3306/somedb?autoReconnect=true";

 //  Database credentials
 static final String USER = "usrname";
 static final String PASS = "pword";

 public static void main(String[] args) {
 Connection conn = null;
 Statement stmt = null;
 try{
    //STEP 2: Register JDBC driver
    Class.forName("com.mysql.jdbc.Driver");

    //STEP 3: Open a connection
    System.out.println("Connecting to database...");
    conn = DriverManager.getConnection(DB_URL,USER,PASS);

    //STEP 4: Execute a query
    System.out.println("Creating statement...");
    stmt = conn.createStatement();
    String sql;
    sql = "SELECT id, name FROM peeps";
    ResultSet rs = stmt.executeQuery(sql);

    //STEP 5: Extract data from result set
    while(rs.next()){
       //Retrieve by column name
       int id  = rs.getInt("id");
       String name = rs.getString("name");

       //Display values
       System.out.print("ID: " + id);
       System.out.println(", name: " + name);
    }
    //STEP 6: Clean-up environment
    rs.close();
    stmt.close();
    conn.close();
 }catch(SQLException se){
    //Handle errors for JDBC
    se.printStackTrace();
 }catch(Exception e){
    //Handle errors for Class.forName
    e.printStackTrace();
 }finally{
    //finally block used to close resources
    try{
       if(stmt!=null)
          stmt.close();
    }catch(SQLException se2){
    }// nothing we can do
    try{
       if(conn!=null)
          conn.close();
    }catch(SQLException se){
       se.printStackTrace();
    }//end finally try
 }//end try
 System.out.println("Goodbye!");
}//end main
}//end FirstExample  

2 个答案:

答案 0 :(得分:2)

你需要这个库 - 不能简化它。以前我猜测你使用像JBoss这样的网络应用服务器为你提供了这个库。现在你在集装箱外面了。

首先从http://dev.mysql.com/downloads/connector/j/5.0.html下载Connector / J jar(包含JDBC驱动程序类com.mysql.jdbc.Driver)。

然后使用当前工作目录中的jar文件,调用你的程序:

java -cp mysql-connector-java-5.n.nn.bin.jar:. somepackage.TestJDBC

另见SO帖子:Including jars in classpath on commandline (javac or apt)

HTH

答案 1 :(得分:1)

将mysql驱动程序jar定位(或上传)到服务器,然后使用

运行代码
java -classpath /path/to/mysql-connector-java-5.0.8-bin.jar:. somepackage.TestJDBC

将版本调整为您正在使用的任何内容。