gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:10:02 27 4
gpt4 key购买 nike

当我尝试从 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

最佳答案

您需要图书馆 - 不能简化它。以前我猜你使用了像 JBoss 这样的 Web 应用程序服务器,它为你提供了这个库。现在你在容器外面。

首先从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

关于java - 从 CentOS 7 终端运行 java 时出现 ClassNotFound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com