0

I am quite new to Java and MySQL. I had followed this video https://www.youtube.com/watch?v=BCqW5XwtJxY&t=557s which allows me to connect localhost mysql to Java but it seems like not working for my code and project. This is my code.

DPAT.java

    public static void main(String[] args) {
    DBConnection connect = new DBConnection();
    connect.getData();
}

DBConnection.java

package dpat;
import java.sql.*;
public class DBConnection {
    private Connection con;
    private Statement st;
    private ResultSet rs;

    public DBConnection()
    {
        try{
            Class.forName("com.mysql.jdbc.Driver");

        con = DriverManager.getConnection("jdbc:mysql://localhost:1234/databasetest","root","");
        st = con.createStatement();
                    }
        catch(Exception ex)
        {
            System.out.println("erro:" + ex);
        }
    }

    public void getData()
    {
        try{
           String query = "select * from tabletest";
           rs = st.executeQuery(query);
            System.out.println("Records from databases");
            while(rs.next())
            {
                int ID = rs.getInt("ID");
                String name = rs.getString("Name");
                int age = rs.getInt("Age");

                System.out.println(" Name: " + name + " ID " + ID + " age " + age );
            }
        }
        catch(Exception ex)
        {
            System.out.println(ex + "error");
        }
    }
}

May I know what is wrong with my code? Thank you very much! :)

James Au
  • 1
  • 1
  • 2
    What exception are you getting? Also a tip: do not publish passwords in internet. – RubioRic Mar 12 '18 at 16:29
  • 2
    *it seems like not working* What doesn't work? Why? What were you expecting? What is happening instead? Is there any error? If yes, please paste the full stack trace in the question, along with the answer to all previous questions. – BackSlash Mar 12 '18 at 16:30
  • 3
    The port is set as 1234, and not just an example? – Lance Toth Mar 12 '18 at 16:31
  • 2
    The default port of MySQL is port 3306, not 1234. Doing things like `System.out.println(ex + "error");` is rarely helpful, if anything use logging, or at minimum `ex.printStackTrace()`, which provides information which you should have included when posting this question. – Mark Rotteveel Mar 12 '18 at 17:50
  • @RubioRic Thanks for reminding. There is nothing shows in my output even exception. The output I expected is the results from my database table – James Au Mar 13 '18 at 03:02
  • @BackSlash Maybe the question is too ambiguous, Thanks for reminding – James Au Mar 17 '18 at 14:25
  • @LanceToth it is the localhost, just an example. Thanks – James Au Mar 17 '18 at 14:25
  • @MarkRotteveel Is 3306 port still applies in localhost? Anyhow, I will give a try. Thanks for the advice – James Au Mar 17 '18 at 14:26
  • Port 3306 is the default unless explicitly configured otherwise. – Mark Rotteveel Mar 17 '18 at 14:29

0 Answers0