Inserting Data Using SQL Statements
Go Up to Modifying Data Using SQL Statements
An executeUpdate statement with an INSERT statement string parameter adds one or more rows to a table. It returns either the row count or 0 for SQL statements that return nothing:
int rowCount= statement.executeUpdate
("INSERT INTO table_name VALUES (val1, val2,…)";
If you do not know the default order of the columns, the syntax is:
int rowCount= statement.executeUpdate
("INSERT INTO table_name (col1, col2,…) VALUES (val1, val2,…)";
The following example adds a single employee to “emp_table”:
//Create a connection object
java.sql.Connection connection =
java.sql.DriverManager.getConnection(url, properties);
//Create a statement object
java.sql.Statement statement = connection.createStatement();
//input the employee data
Java.lang.String fname;
Java.lang.String lname;
Java.lang.String empno;
System.in.readln("Enter first name: ", + fname);
System.in.readln("Enter last name: ", + lname);
System.in.readln("Enter employee number: ", + empno);
//insert the new employee into the table
int rowCount = statement.executeUpdate
("INSERT INTO emp_table (first_name, last_name, emp_no)
VALUES (fname, lname, empno)");