简体   繁体   中英

JDBC classnotfound exception

I recently started JDBC. I installed JDBC drivers from ubuntu software center and run my first java program using JDBC.

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();
            }
        }
    }
}

I created "emp" database and I am trying to browse its content using JDBC. when i use

javac db.java

everything works ok. However when I run it via

java db

it gives me java.lang.classnotfoundException. I included CLASSPATH=CLASSPATH://user/share/java/mysql-connector-java.jar into bashrc file. Can anybody help me to solve this problem?

  • Put Class.forName("com.mysql.jdbc.Driver"); before DriverManager.getConnection() call, not after it
  • DriverManager.getConnection() needs URL as a parameter, not driver class name, so use Connection conn=DriverManager.getConnection(DB_URL);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM