insert query in java code example

Example 1: java sql statement insert example

import java.sql.*;

/**
 * JdbcInsert1.java - Demonstrates how to INSERT data into an SQL
 *                    database using Java JDBC.
 */
class JdbcInsert1 { 
  
    public static void main (String[] args) { 
        try { 
            String url = "jdbc:msql://200.210.220.1:1114/Demo"; 
            Connection conn = DriverManager.getConnection(url,"",""); 
            Statement st = conn.createStatement(); 
            st.executeUpdate("INSERT INTO Customers " + 
                "VALUES (1001, 'Simpson', 'Mr.', 'Springfield', 2001)"); 
            st.executeUpdate("INSERT INTO Customers " + 
                "VALUES (1002, 'McBeal', 'Ms.', 'Boston', 2004)"); 
            st.executeUpdate("INSERT INTO Customers " + 
                "VALUES (1003, 'Flinstone', 'Mr.', 'Bedrock', 2003)"); 
            st.executeUpdate("INSERT INTO Customers " + 
                "VALUES (1004, 'Cramden', 'Mr.', 'New York', 2001)");

            conn.close(); 
        } catch (Exception e) { 
            System.err.println("Got an exception! "); 
            System.err.println(e.getMessage()); 
        } 
  
    }
}

Example 2: WAP in Java to insert a record from a form to table.

import java.io.DataInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class ExPrepareStatement {
	public static void main(String[] args) {
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();

			//serverhost = localhost, port=3306, username=root, password=123
			Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","123");

			DataInputStream KB=new DataInputStream(System.in);

			//input employee id
			System.out.print("Enter Employee ID: ");
			String eid=KB.readLine();
			//input employee name
			System.out.print("Enter Employee Name: ");
			String en=KB.readLine();
			//input employee Date Of Birth
			System.out.print("Enter Employee Date Of Birth: ");
			String ed=KB.readLine();
			//input employee city
			System.out.print("Enter Employee City: ");
			String ec=KB.readLine();
			//input employee Salary
			System.out.print("Enter Employee Salary: ");
			String es=KB.readLine();

			//creating object of PreparedStatement class and passing parameter (?)
			PreparedStatement smt=cn.prepareStatement("insert into employees values(?,?,?,?,?)");

			// set the values
			smt.setString(1, eid);
			smt.setString(2, en);
			smt.setString(3, ed);
			smt.setString(4, ec);
			smt.setInt(5, Integer.parseInt(es));

			//to execute update
			smt.executeUpdate();
			System.out.println("Record Submitted....");
			
			//close the file
			cn.close();
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}

Tags:

Sql Example