Insert Date Into Database Postgres JDBC

Viewed 9401

I'm new to Java and also to Postgres.

I have a little project about restaurant and i have a struk(eng: bill) table like this:

enter image description here

and I have a method to inserting information into that table like this:

public int insertBill(int id_karyawan, String tanggal, String waktu, int total) {
    String SQL = "INSERT INTO struk(kode, id_karyawan, tanggal, waktu, total) VALUES (?,?,?,?,?)";
    int id = 0;

    try(Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS)) {
        pstmt.setInt(1, 1);
        pstmt.setInt(2, id_karyawan);
        pstmt.setString(3, tanggal);
        pstmt.setString(4, waktu);
        pstmt.setInt(5, total);

        int affectedRows = pstmt.executeUpdate();
        if(affectedRows > 0) {
            try(ResultSet rs = pstmt.getGeneratedKeys()) {
                if(rs.next()) {
                    id = rs.getInt(1);
                }
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
        }
    } catch (SQLException ex) {
        System.out.println(ex.getMessage());
    }
    return id;
}

later, that method will called with this:

int billID = app.insertBill(1, "2017-09-24", "08:00:00", 150000);

The problem is, i dont have any idea about the Date and the time, what should i pass as a parameter? what kind of variable so that the query work well? I've searched about it got some clue to use string. I use string on a query method for now. Any advice?

2 Answers

Hope this will help you:

public int insertBill(int id_karyawan, String tanggal, String waktu, int total) {
String SQL = "INSERT INTO struk(kode, id_karyawan, tanggal, waktu, total) VALUES (?,?,?,?,?)";
int id = 0;

try(Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS)) {
    pstmt.setInt(1, 1);
    pstmt.setInt(2, id_karyawan);
    pstmt.setDate(3, java.sql.Date.valueof("2017-09-24")); 
    pstmt.setTime(4, java.sql.Time.valueof("08:00:00")); 
    pstmt.setInt(5, total);

    int affectedRows = pstmt.executeUpdate();
    if(affectedRows > 0) {
        try(ResultSet rs = pstmt.getGeneratedKeys()) {
            if(rs.next()) {
                id = rs.getInt(1);
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
} catch (SQLException ex) {
    System.out.println(ex.getMessage());
}
return id;

}
Related