Connect MySQL with JDBC driver

To connect mysql with jdbc driver mysql-connector-java-{version}bin.jar needed in your class path.

To process any SQL statement with JDBC, follow these steps:

  • Establishing a connection.
  • Create a statement.
  • Execute the query.
  • Process the ResultSet object.
  • Close the connection.

JDBCPreparedStatementExample.java

package com.javahonk;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCPreparedStatementExample {

    public static void main(String[] args) {

	Connection connection = null;
	PreparedStatement preparedStatement = null;

	try {
	    // Register JDBC Driver
	    Class.forName("com.mysql.jdbc.Driver");
	    // Open connection
	    connection = DriverManager.getConnection(
		    "jdbc:mysql://localhost:3306/javahonk", "root",
		    "admin");
	    // Create query set value and execute statement
	    String sql = "INSERT INTO employee(First_Name, Last_Name)"
	    	+ " VALUES(?, ?)";
	    preparedStatement = connection.prepareStatement(sql);
	    preparedStatement.setString(1, "Java");
	    preparedStatement.setString(2, "Honk");
	    preparedStatement.executeUpdate();

	    System.out
		    .println("Value inserted successfully"
		    	+ " to employee table");

	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		if (connection != null) {
		    connection.close();
		}
		if (preparedStatement != null) {
		    preparedStatement.close();
		}
	    } catch (SQLException e) {
		e.printStackTrace();
	    }
	}

    }

}

 

  • That’s it for connect MySQL with JDBC driver

Leave a Reply

Your email address will not be published. Required fields are marked *