Java - Getting Data from MySQL database

前端 未结 6 494
南笙
南笙 2021-02-04 15:31

I\'ve connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).

I am trying to get the

6条回答
  •  终归单人心
    2021-02-04 15:52

    Here is what I just did right now:

    import java.sql.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import com.sun.javafx.runtime.VersionInfo;  
    
    public class ConnectToMySql {
    public static ConnectBean dataBean = new ConnectBean();
    
    public static void main(String args[]) {
        getData();
        }
    
    
    
    public static void getData () {
    
        try {
            Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
     "root", "root");
            
     // here mynewpage is database name, root is username and password
        
    Statement stmt = con.createStatement();
            System.out.println("stmt  " + stmt);
            ResultSet rs = stmt.executeQuery("select * from carsData");
            System.out.println("rs  " + rs);
            int count = 1;
            while (rs.next()) {
                String vehicleType = rs.getString("VHCL_TYPE");
                System.out.println(count  +": " + vehicleType);
                count++;
    
            }
    
            con.close();
        } catch (Exception e) {
            Logger lgr = Logger.getLogger(VersionInfo.class.getName());
            lgr.log(Level.SEVERE, e.getMessage(), e);
    
            System.out.println(e.getMessage());
        }
        
        
    }
    
    }
    

    The Above code will get you the first column of the table you have.

    This is the table which you might need to create in your MySQL database

    CREATE TABLE
    carsData
    (
        VHCL_TYPE CHARACTER(10) NOT NULL,
    );
    

提交回复
热议问题