Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;

public class Main {
    private static final String DRIVER = "com.mysql.jdbc.Driver";

    private static final String URL = "jdbc:mysql://localhost/testdb";

    private static final String USERNAME = "root";

    private static final String PASSWORD = "";

    public static void main(String[] args) throws Exception {

        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM users");

        ResultSetMetaData metadata = resultSet.getMetaData();
        int columnCount = metadata.getColumnCount();

        ArrayList<String> columns = new ArrayList<String>();
        for (int i = 1; i < columnCount; i++) {
            String columnName = metadata.getColumnName(i);
            columns.add(columnName);
        }

        while (resultSet.next()) {
            for (String columnName : columns) {
                String value = resultSet.getString(columnName);
                System.out.println(columnName + " = " + value);
            }
        }
    }
}