A simple step-by-step guide for connecting simple console-based Java application with MySQL database.
Tools required:
- Eclipse IDE for Java
- HiediSQL IDE for interfacing with MYSQL
Follow these steps:
- Open HiediSQL and enter the username and password(typically username=root and password=root)

- Create a simple database with a table and a few columns like the one shown here. the database names test_db having a table called customer with customerNumber, customerName and address.

- now download java SQL connector JAR file from: https://dev.mysql.com/downloads/connector/j/5.0.html

- Create a new java application in eclipse (DatabaseConnectivity in our example)
- Select the newly created java project (DatabaseConnectivity), right-click on it, goto build path and then select add external jar file.
Browse to the location where you have downloaded java mysqlconnector jar file and press ok to include it in your project. This external connector will help your code to communicate with MySQL database. - write the following code:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;public class DatabaseConnection {
public static void main(String[] args) {
Connection connect = null;
Statement statement=null;
ResultSet resultset = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
connect = (Connection) DriverManager.getConnection(“jdbc:mysql://localhost/test_db”,”root”,”root” );
if(connect != null){
System.out.println(“Database connected”);
}else{
System.out.println(“Database connection failed”);
}
} catch (Exception e ) {
e.printStackTrace();
}try {
statement = (Statement) connect.createStatement();
// Result set get the result of the SQL query
resultset = statement.executeQuery(“select * from customers”);while(resultset.next()){
System.out.print( resultset.getInt(“customerNumber”)+” “);
System.out.print(resultset.getString(“customerName”)+’\n’);
}} catch (SQLException e) {
e.printStackTrace();
}
}}
- Select the project, right click on it, goto run as and select java application.
- See the output in the console.

This is simple code for database connectivity and selecting data out from a table.
You may now create your application with insert, update, delete and other select queries.
That’s it folks!
Code On!
Thank You 😀






