Java PreparedStatement: A SQL INSERT example

Java PreparedStatement FAQ: Can you share an example of a Java PreparedStatement that executes a SQL INSERT query?

Yes ... I just realized I don’t have a Java PreparedStatement SQL INSERT example out here, so, let’s correct that. Here’s the source code for a Java/JDBC PreparedStatement INSERT query example:

//
// A simple Java JDBC PreparedStatement example using a SQL INSERT.
//
public void addUser(User user, Connection conn)
throws SQLException
{
  String query = "INSERT INTO Users ("
    + " user_id,"
    + " username,"
    + " firstname,"
    + " lastname,"
    + " companyname,"
    + " email_addr,"
    + " want_privacy ) VALUES ("
    + "null, ?, ?, ?, ?, ?, ?)";

  try {
    // set all the preparedstatement parameters
    PreparedStatement st = conn.prepareStatement(query);
    st.setString(1, user.getName());
    st.setString(2, user.getFirstName());
    st.setString(3, user.getLastName());
    st.setString(4, user.getCompanyName());
    st.setString(5, user.getEmail());
    st.setString(6, user.getPrivacy());

    // execute the preparedstatement insert
    st.executeUpdate();
    st.close();
  } 
  catch (SQLException se)
  {
    // log exception
    throw se;
  }
}

I hope it’s helpful to have examples out here like this Java PreparedStatement SQL INSERT example. I don’t have a very good memory, so I like to keep a lot of Java/JDBC examples like this out here.