Java - Getting Data from MySQL database

前端 未结 6 476
南笙
南笙 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 16:07

    Something like this would do:

    public static void main(String[] args) {
    
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
    
        String url = "jdbc:mysql://localhost/t";
        String user = "";
        String password = "";
    
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();
            rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
    
            if (rs.next()) {//get first result
                System.out.println(rs.getString(1));//coloumn 1
            }
    
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(Version.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
    
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }
    
            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(Version.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
    }
    

    you can iterate over the results with a while like this:

    while(rs.next())
    {
    System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
    }
    

    There are many other great tutorial out there like these to list a few:

    • http://www.vogella.com/articles/MySQLJava/article.html
    • http://www.java-samples.com/showtutorial.php?tutorialid=9

    As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself

    References:

    • http://zetcode.com/databases/mysqljavatutorial/

提交回复
热议问题