INSERT statement

The SQL statement that creates (populates) data in the database has the following format:

INSERT INTO table_name (column1,column2,column3,...)
   VALUES (value1,value2,value3,...);

When several tables records have to be added, it looks like this:

INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...), (value11,value21,value31,...), ...;

Before writing a program, let's test our INSERT statement:

It worked without an error and returned the number of inserted rows as 1, so we are going to create the following method:

void executeStatement(String sql){
Connection conn = getConnection();
try (conn; Statement st = conn.createStatement()) {
st.execute(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
}

We can execute the preceding method and insert another row:

executeStatement("insert into person (first_name, last_name, dob)" +
" values ('Bill', 'Grey', '1980-01-27')");

We will see the result of this and previous INSERT-statement execution in the next section, when we demonstrate SELECT-statement.

Meanwhile, we would like to discuss the most popular methods of the java.sql.Statement interface:

        void executeStatement(String sql){
Connection conn = getConnection();
try (conn; Statement st = conn.createStatement()) {
System.out.println(st.execute(sql)); //prints: false
System.out.println(st.getResultSet()); //prints: null
System.out.println(st.getUpdateCount()); //prints: 1
} catch (SQLException ex) {
ex.printStackTrace();
}
}
        void executeStatement(String sql){
Connection conn = getConnection();
try (conn; Statement st = conn.createStatement()) {
System.out.println(st.executeQuery(sql)); //prints: ResultSet
System.out.println(st.getResultSet()); //prints: ResultSet
System.out.println(st.getUpdateCount()); //prints: -1
} catch (SQLException ex) {
ex.printStackTrace();
}
}
        void executeStatement4(String sql){
Connection conn = getConnection();
try (conn; Statement st = conn.createStatement()) {
System.out.println(st.executeUpdate(sql));//prints: 1
System.out.println(st.getResultSet()); //prints: null
System.out.println(st.getUpdateCount()); //prints: 1
} catch (SQLException ex) {
ex.printStackTrace();
}
}