-1

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?

import java.sql.*;

class Test{
    public static void main(String arg[]){
        try{
            String query="select * from photo ";
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection
                    ("jdbc:mysql://localhost/mydb","user","password");
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery(query);
            rs.next();
            String sname=rs.getString(2); 
            System.out.println(sname);
            con.close();
        }
        catch(Exception e)
        {
            System.out.println("error ");
        }
    }
}
Stein Åsmul
  • 37,754
  • 24
  • 87
  • 158
user3363800
  • 11
  • 1
  • 4

2 Answers2

1

First of all remove the space at the end of the query

String query="select * from photo ";

Next try giving the port in the url

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");

Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver you need to add the mysql-connector.jar in your classpath.Get the jar from here

Well if you are using command prompt you can run like this

java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className

If you are using elipse then download the jar and add it to the classpath like this

Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done

SparkOn
  • 8,543
  • 4
  • 27
  • 30
  • Well if it worked then you can accept it as you answer so that it might help someone else to easily rectify the problem – SparkOn Jul 12 '14 at 14:35
0

1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost" Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password"); 2> should download and add mysql-connector-java to library Hope this would help

linh
  • 9
  • 3