简体   繁体   中英

Java to MySQL connection error

I am still relatively new to programming and this is my first attempt to create a program with a database. I created the database in PhpMyAdmin. There is no errors between the two classes used to access the database but it does not print the required info. Just wondering if anyone more experienced then me can see where I have gone wrong. Thanks

The Main method is as follows:

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

Then the DBConnect method is as follows:

import java.sql.*;

public class DBConnect {
    private Connection con;
    private Statement st;
    private ResultSet rs;

    public DBConnect(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:8080/software","root","usbw");
            st = con.createStatement();
        }catch(Exception ex){
            System.out.println("Error:" + ex);
        }
    }

    public void getData(){
        try{
            String query="select from * football";
            rs = st.executeQuery(query);
            System.out.print("Records from the database");
            while(rs.next()){
                String name = rs.getString("Name");
                System.out.print("Name: "+name+" ");
            }
        }catch(Exception ex){
            System.out.println(ex);
        }
    }
}

If anyone can see where the problem lies or has any other sort of advice it would be greatly appreciated

thanks again

You have incorrect query

select from * football

It should be

select * from football

Also check, that you have correct mysql port. I guess it should be 3306, but not 8080.

Try this:

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/software", "root", "usbw");
    Statement st = con.createStatement();
    String query="select * from football";
    ResultSet rs = st.executeQuery(query);
    System.out.print("Records from the database");
    while(rs.next()){
        String name = rs.getString("Name");
        System.out.print("Name: "+name+" ");
    }
}

Your SQL sentence is select from * football , and should be select * from football .

Another thing, you are connecting to mysql using 8080 port, is that correct ?? Generally MySQL listen in 3306 port.

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