JDBC classnotfound异常

时间:2015-12-02 13:14:09

标签: java mysql bash ubuntu jdbc

我最近开始使用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文件中。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

  • Class.forName("com.mysql.jdbc.Driver");来电之前放DriverManager.getConnection(),而不是之后
  • DriverManager.getConnection()需要将URL作为参数,而不是驱动程序类名称,因此请使用Connection conn=DriverManager.getConnection(DB_URL);
相关问题