我最近开始使用 JDBC。我从 ubuntu 软件中心安装了 JDBC 驱动程序,并使用 JDBC 运行我的第一个 java 程序。
import java.sql.*
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/emp";
static final String USER= "username";
static final String PASS="password";
public static void main(String [] args)
{
Connection conn=DriverManager.getConnection(JDBC_DRIVER);
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
System.out.println("Creting statement");
String sql;
stmt=conn.createStatement();
sql="select id, first last, age from Employee";
ResultSet rs= stmt.executeQuery(sql);
while(rs.next())
{
int id=rs.getInt("id");
int age=rs.getInt("age");
String first=rs.getString("first");
String last=rs.getString("Last");
System.out.print("ID: "+id);
System.out.print(", Age: " +age);
System.out.print(", First: "+first);
System.out.println(", Last: "+last);
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
}
}
}
我创建了“emp”数据库,并尝试使用 JDBC 浏览其内容。当我使用时
javac db.java
一切正常。但是当我通过
运行它时java db
它给了我 java.lang.classnotfoundException。我将 CLASSPATH=CLASSPATH://user/share/java/mysql-connector-java.jar 包含到 bashrc 文件中。谁能帮我解决这个问题吗?
最佳答案
- 将
Class.forName("com.mysql.jdbc.Driver");
放在DriverManager.getConnection()
调用之前,而不是之后- 请注意,您也可能不再需要它 - 请参阅 Class.forName(JDBC_DRIVER) no longer needed?
DriverManager.getConnection()
需要 URL 作为参数,而不是驱动程序类名,因此使用Connection conn=DriverManager.getConnection(DB_URL);
关于java - JDBC 类未找到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34043677/