Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeffersonchaves/5261b8cfe699d76aed5857711a52c9ce to your computer and use it in GitHub Desktop.
Save jeffersonchaves/5261b8cfe699d76aed5857711a52c9ce to your computer and use it in GitHub Desktop.
public class SellerRepository {
private Connection conn;
private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public SellerRepository(){
ConnectionFactory connectionFactory = new ConnectionFactory();
conn = connectionFactory.getConnection();
}
public void insertWithGeneratedKeys(){
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = conn.prepareStatement("INSERT INTO seller (Name, Email, BirthDate, BaseSalary, DepartmentId) VALUES (?, ?, ?, ?, ?)", statement.RETURN_GENERATED_KEYS);
statement.setString(1, "Jeff Cyan");
statement.setString(2, "jeff@gmail.com");
statement.setDate(3, new java.sql.Date(sdf.parse("22/04/1985").getTime()));
statement.setDouble(4, 1500.0);
statement.setInt(5, 4);
int rowsAffected = statement.executeUpdate();
System.out.println(rowsAffected + " row(s) affected.");
if (rowsAffected > 0) {
ResultSet rs = statement.getGeneratedKeys();
while (rs.next()) {
int id = rs.getInt(1);
System.out.println("Done! Id: " + id);
}
} else {
System.out.println("No rows affected!");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment