JDBC insert example (Statement)
In this blog we will insert a record into the database using Statement. For this we need to add following dependencies into our pom.xml.
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> [addToAppearHere]
For inserting record into the database we need to do following:
connection = getConnection();
statement = connection.createStatement();
//Executing SQL statement
statement.executeUpdate(sqlQuery);
The full example is following:
package com.javajdbc.example; public final class DatabaseConfiguration { /** * Mysql driver class name */ public static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; /** * The URL */ public static final String URL = "jdbc:mysql://localhost:3306/techblog"; /** * The username */ public static final String USERNAME = "root"; /** * The password */ public static final String PASSWORD = "root"; private DatabaseConfiguration() { // no initialization } }
package com.javajdbc.example; import org.apache.commons.dbutils.DbUtils; import java.sql.*; import static com.javajdbc.example.DatabaseConfiguration.*; public class JDBCSInsertExample { public static void main(String[] argv) { final JDBCSInsertExample JDBCSInsertExample = new JDBCSInsertExample(); final Connection connection = JDBCSInsertExample.getConnection(); if (connection != null) { System.out.println("You are successfully created a connection..."); } else { System.out.println("Failed to create a connection..."); } JDBCSInsertExample.inserUser(); } private void inserUser() { Connection connection = null; Statement statement = null; String sqlQuery = "INSERT INTO USER (ID, NAME) VALUES (1,'user1')"; try { connection = getConnection(); statement = connection.createStatement(); //Executing SQL statement statement.executeUpdate(sqlQuery); System.out.println("User has been successfully inserted!"); } catch (SQLException e) { System.out.println(e.getMessage()); } finally { DbUtils.closeQuietly(statement); DbUtils.closeQuietly(connection); } } /** * * @return the jdbc connection */ private Connection getConnection() { try { //Loading the driver class Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println(e); } Connection connection = null; try { //Attempts to establish a connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { System.out.println(e); } return connection; } } [addToAppearHere]
And the output should be following:
You are successfully created a connection... User has been successfully inserted!