java JDBC classnotfound异常
我最近开始使用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连接器java。jar转换为bashrc文件。有人能帮我解决这个问题吗
# 1 楼答案
Class.forName("com.mysql.jdbc.Driver");
放在DriverManager.getConnection()
调用之前,而不是之后DriverManager.getConnection()
需要URL作为参数,而不是驱动程序类名,所以使用Connection conn=DriverManager.getConnection(DB_URL);