Way2Java

Insert Record JDBC Keyboard Input

To take record particulars from keyboard and insert them in the Employee table.

Note: See that there exists an Employee table by the time this program is executed. This can be done with Create Table.

Example on Insert Record JDBC Keyboard Input
import java.sql.*;                                     // for JDBC classes
import java.io.*;                                      // for keyboard reading

public class KeyboardInsert
{
  public static void main(String args[]) throws Exception
  {                                                    // standard database connections
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:snrao", "scott", "tiger");
    Statement stmt = con.createStatement();
                                                       // keyboard input
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter Employee ID:");
    int id = Integer.parseInt(br.readLine());

    System.out.println("Enter Employee Name:");
    String name = br.readLine();

    System.out.println("Enter Employee Salary:");
    double salary = Double.parseDouble(br.readLine());

    stmt.executeUpdate("insert into Employee values("+id+ ", '"+name+"',"+salary+")");
                                                      =// now record inserted (of Insert Record JDBC Keyboard Input)
    System.out.println(name + " record inserted");

    stmt.close();
    con.close();
   }
 } 

stmt.executeUpdate(“insert into Employee values(“+id+ “, ‘”+name+”‘,”+salary+”)”);

Observe the single quotes and double quotes in the above statement. empname is varchar and requires single quotes. Always get the variable outside the string.

The above code works for one record. By keeping in a loop, multiple records can be inserted.

Note 1: Before going into the program, it is advised to go through JDBC Programming Basic Steps where the meaning of Connection, Statement etc. are discussed.

Note 2: To know how to use try-catch-finally with the above code, example program is available at JDBC Example – Create Table.