java mysql database connection

JDBC | MySQL Connection

This tutorial will show you How to connect with MySQL Database?

Tushar Patil
2 min readJan 14, 2022

--

Step 1: Download MySQL Workbench (Community). Also Download MySQL Connector jar. It's inside zip extract somewhere on your machine.

Step 2: Now install the MySQL workbench. Note: Let the username password be root(you can set custom values)

Step 3: Create a Database like (Test) and a table inside of it (users). Add some user records like name and email id. Assuming you guys know MySQL

Step 4: Open Eclipse and create a new java project. Create a class with the main method.

Add MySQL connector jar file to project. Right-click on project folder > BuildPath > Configure Build Path > Add External Jar > Locate to the connector jar file.

Step 5: Copy-paste the code below in java file

Connection conncetion = null;

try {

Class.forName(“com.mysql.jdbc.Driver”);

conncetion = DriverManager.getConnection(“jdbc:mysql://localhost:3306/restdb”, “root”, “root”);

//“jdbc:mysql://localhost:3306/Test” -> is url(if its a remote db then mention ip addr), “root”> is user, “root”-> password

Statement stmt = conncetion.createStatement();

System.out.println(“Created Connection”);

ResultSet rs = stmt.executeQuery(“select * from users”);

while (rs.next())

System.out.println(rs.getString(1)+” — “+rs.getString(2));

conncetion.close();

} catch (SQLException | ClassNotFoundException e) {

e.printStackTrace();

}finally {

try {

conncetion.close();

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

}

Note: Above is just an example for retrieval of records. You can follow this documentation

Hope this was helpful. Thanks!

--

--