In order to connect to MySQL database, Follow below steps
- Load JDBC Driver
- Create Connection object (By passing url, username and password)
- Create statement object (from Connection object)
- Execute query (from Statement object)
- Close connection
import java.sql.*; public class MySqlConnection { public static void main(String args[]) { try { // Step-1: Load JDBC Driver class Class.forName("com.mysql.jdbc.Driver"); // Step-2: Create Connection object Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase", "root", "admin"); // Step-3: Create Statement object (Statement, PreparedStatement or CallableStatement) Statement stmt = con.createStatement(); // Step-4: Execute query (In case of PreparedStatement or CallableStatement use executeUpdate method) ResultSet rs = stmt.executeQuery("select * from emp"); // Process resultset while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3)); //Step-5: Close connection con.close(); } catch (Exception e) { // Handle Exception here } } }
Class.forName(String arg)
is a static method of Class which is used to load classes using reflection.
DriverManager
is a basic service for managing a set of JDBC drivers.
Statement
is the factory for resultset. It is used for general purpose access to the database. It executes a static SQL query at runtime.
PreparedStatement
is used when we need to provide input parameters to the query at runtime.
CallableStatement
is used when we need to access the database stored procedures. It can also accept runtime parameters.