0

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?

olzha bala
  • 183
  • 1
  • 5
  • 15
  • If you are using any IDE add the jar file in the `WEB-INF/lib`, if it is a web-app, add it to `lib` folder and try it. – Subramanyam M Dec 02 '15 at 13:19
  • I strongly encourage you to use a build and dependency management tool like Maven, Ant + Ivy, Gradle, etc. instead of manually compile and set the classpath. – Eric Citaire Dec 02 '15 at 15:03

1 Answers1

0
  • 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);
Community
  • 1
  • 1
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43