0

I have a column of date type (daterecord) in PostgreSql and jdatechooser component in java (dateChooser). I am trying to insert the selected date into my database with this initial code:

Date daterec = dateChooser.getDate();
String sql= "INSERT INTO date values (?)";
pst.prepareStatement(sql);
pst.setDate(1, daterec);
pst.execute();

..but I know my setDate code is wrong..please help what to do?

Jerson Calinawan
  • 47
  • 1
  • 2
  • 8
  • 1
    What do you mean with "*my setDate code is wrong*"? This looks fine to me (although it's better to use `executeUpdate()` instead of `execute()` in this case) –  Nov 15 '14 at 08:45
  • What is the stacktrace? What errors are you getting? – Mladen Uzelac Nov 15 '14 at 10:31
  • Postgres does not have any `daterecord` data type amongst [its date-time types](http://www.postgresql.org/docs/current/static/datatype-datetime.html). – Basil Bourque Jul 03 '15 at 19:08
  • possible duplicate of [Java Date - Insert into database](http://stackoverflow.com/questions/1081234/java-date-insert-into-database) – Basil Bourque Jul 03 '15 at 19:09
  • the code looks fine (although `date` is a horrible name for a table) - what is the exact problem you have? Please [edit] your question and add the complete `create table` statement for your table –  Dec 27 '16 at 07:54

1 Answers1

0

i can tell you how to insert a date record into a mysql table by using the Datechooser control..it is how i do it..so it may differ from your point of view

public void getdate() {
    DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
    String s=df.format(jDateChooser1.getDate());
    jLabel1.setText(""+s);
}

public void insert(){
    try{
        Class.forName("java.sql.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost/<database_name>","root","<db password>"); 
        Statement stmt=con.createStatement();
        String query="insert into test  values('"+jLabel1.getText()+"')";
        stmt.executeUpdate(query);
        JOptionPane.showMessageDialog(null,"Insert successful");
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(null,"Error in connectivity");
    }
}    
jean-max
  • 1,640
  • 1
  • 18
  • 33
  • 1
    Do **not** concatenate user input into a SQL string. Use a `PreparedStatement` and never pass a `date` value as a plain string. –  Dec 27 '16 at 07:53