How to insert data into a MySQL database with Java?


To insert data into MySQL database, use INSERT command. The syntax is as follows −

INSERT INTO yourTableName(yourColumnName1,........yourColumnNameN)values(Value1,Value2,......ValueN);

Here, I am inserting records in a MySQL database with JAVA programming language. First, we need to create a table in MySQL. The query is as follows −

mysql> create table InsertDemo
   -> (
   -> Id int,
   -> Name varchar(200),
   -> Age int
   -> );
Query OK, 0 rows affected (0.97 sec)

Now, here is the JAVA code to insert records into MySQL database with table InsertDemo. . Before that, we will establish a Java Connection to our MySQL database −

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaInsertDemo {
   public static void main(String[] args) {
      Connection conn = null;
      Statement stmt = null;
      try {
         try {
            Class.forName("com.mysql.jdbc.Driver");
         } catch (Exception e) {
            System.out.println(e);
      }
      conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/business", "Manish", "123456");
      System.out.println("Connection is created successfully:");
      stmt = (Statement) conn.createStatement();
      String query1 = "INSERT INTO InsertDemo " + "VALUES (1, 'John', 34)";
      stmt.executeUpdate(query1);
      query1 = "INSERT INTO InsertDemo " + "VALUES (2, 'Carol', 42)";
      stmt.executeUpdate(query1);
      System.out.println("Record is inserted in the table successfully..................");
      } catch (SQLException excep) {
         excep.printStackTrace();
      } catch (Exception excep) {
         excep.printStackTrace();
      } finally {
         try {
            if (stmt != null)
               conn.close();
         } catch (SQLException se) {}
         try {
            if (conn != null)
               conn.close();
         } catch (SQLException se) {
            se.printStackTrace();
         }  
      }
      System.out.println("Please check it in the MySQL Table......... ……..");
   }
}

Here is the sample output −

To check the record is inserted or not into table, use SELECT statement. The query is as follows −

mysql> select *from InsertDemo;

Here is the output −

+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
|    1 | John  |   34 |
|    2 | Carol |   42 |
+------+-------+------+
2 rows in set (0.00 sec)

As you can see above, we have inserted records in a MySQL database successfully.

Updated on: 30-Jul-2019

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements