Inserting data in a database table

Here’s an example that populates a customer table. Basically, get a statement from a connection and call executeUpdate passing in the insert SQL statement.

Notice that this answer is using plain JDBC. Maybe you would like to check out JPA these days (Hibernate, EclipseLink, …)

Main.java:

import java.util.*;
import java.sql.*;
  
public class Main {
   public static void main(String []args) {
      try {
         Database db = new Database("org.gjt.mm.mysql.Driver",
                                    "jdbc:mysql://192.168.0.1/esus",
                                    "joris",
                                    "mypass");
         Connection con = db.getConnection();
         CustomerDAO custDAO = new CustomerDAO(con);
 
         Customer cust1 = new Customer("Joris Van den Bogaert", "joris1@esus.com");
         Customer cust2 = new Customer("Alicia Kolesnikova", "alicia1@esus.com");
 
         custDAO.insert(cust1);
         custDAO.insert(cust2);
 
         db.close();
      }
      catch(DatabaseException e) {
         e.printStackTrace();
      }
   }
}
 
class Customer
{
   private String name;
   private String email;
 
   public Customer(String name, String email) {
      setName(name);
      setEmail(email);
   }
 
   public String getName() {
      return name;
   }
 
   public String getEmail() {
      return email;
   }
}
 
class Database
{
   Connection connection = null;
  
   public Database(String driver, String url, String user, String pass) 
                      throws DatabaseException 
   {
      try {
         Class.forName(driver).newInstance();
 
         connection = DriverManager.getConnection(url, user, pass);
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   }
 
   public Connection getConnection() {
      return connection;
   }
 
   public void close() throws DatabaseException {
      try {
         connection.close();
      }
      catch(Exception e) {
         throw new DatabaseException(e.getMessage());
      }
   } 
}   
 
class DatabaseException extends Exception {
   public DatabaseException() {
   }
 
   public DatabaseException(String message) {
      super(message);
   }
}
 
class CustomerDAO 
{
   Connection connection = null;
 
   public CustomerDAO(Connection connection) {
      this.connection = connection;
   }
 
   public void insert(Customer cust) throws DatabaseException {
      try {
         PreparedStatement stmt = connection.createPreparedStatement();
         stmt.executeUpdate("INSERT INTO customers (name, email) " + 
                            "VALUES (?, ?)'");
         stmt.setString(1, cust.getName());
         stmt.setString(2, cust.getEmail());
         stmt.close();
      }
      catch(SQLException e) {
         throw new DatabaseException(e.getMessage());
      }
   }
}