我有一个 java 文件 hello.java
,它有一个 JDBC 连接,在运行它时,我收到错误(Ubuntu 18.04 LTS):
javac hello.java
java hello
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at hello.main(hello.java:22)
Goodbye!
当我尝试使用类路径时,它给出:
javac -cp /usr/share/java/mysql-connector-java-8.0.23.jar hello.java
java -cp /usr/share/java/mysql-connector-java-8.0.23.jar hello
Error: Could not find or load main class hello
我也试过mysql-connector-java-5.1.45.jar,还是一样的问题。
而 java -version
给出:
openjdk version "1.8.0_282"
OpenJDK Runtime Environment (build 1.8.0_282-8u282-b08-0ubuntu1~18.04-b08)
OpenJDK 64-Bit Server VM (build 25.282-b08, mixed mode)
我尝试了以下问题:
但是没有得到满意的结果。有谁知道如何解决这个问题?
这是我的代码,hello.java
:
//STEP 1. Import required packages
import java.sql.*;
public class hello {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/data";
// Database credentials
static final String USER = "newuser";
static final String PASS = "password";
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 * from temp";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
//Handle errors for JDBC
e.printStackTrace();
} finally{
//finally block used to close resources
try{
if(stmt!=null) {
stmt.close();
}
}catch(SQLException se){
// nothing we can do
se.printStackTrace();
}
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
System.out.println("Goodbye!");
}//end main
}//end FirstExample
}
答案 0 :(得分:1)