我最近启动了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 classnotfound异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34043677/