How to Display All Records Using JDBC in Java


Through this example, we may see how to use JDBC to connect to Mysql database and perform table lookup operations.
Start by creating a test database in Mysql:
![](testDatabase.png)

Source Code

package com.beginner.examples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCConnectMySql {

	public static void main(String[] args) {

		try {

			// The load driver
			Class.forName("org.gjt.mm.mysql.Driver");

			// The url of the database
			String url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=false";

			// Get the Connection object
			Connection connection = DriverManager.getConnection(url, "root",
					"root");
			// Create an object to execute the SQL statement
			Statement statement = connection.createStatement();

			// Execute SQL statement :show table,the execution results are
			// stored in a ResultSet
			ResultSet tables = statement.executeQuery("show tables");
			
			System.out.println("All the tables:");
			
			//Iterative ResultSet
			while (tables.next()) {
				
				String tableString = tables.getString("Tables_in_test");
				
				System.out.println(tableString);
			}

			//Close the connection
			connection.close();


		} catch (Exception e) {

			e.printStackTrace();
		}

	}

}

Output:

All the tables:
table_1
table_2
table_3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments