0

1- a me tried in this way

 String sql = "insert into transport(s_id,transport_date)" +
            " values (  + jTextField2.getText()+","
                     + ((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText() +")"; 

pst=con .prepareStatement(sql2);
             pst.executeUpdate();

2- and this way

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
  String date=sdf.format(jDateChooser1.getDate());

String sql = "insert into transport(s_id,transport_date)" +
            " values (  + jTextField2.getText()+","
                     +  date +")"; 

in #run examble today choose : 2021-5-27 will insert 1989 !

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    How about using a [PreparedStatement](https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html) and a setDate method? – Gilbert Le Blanc May 27 '21 at 12:42
  • 1
    1) The first code snippet, at least, does not look like it would even compile. For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) While debugging, factor out all the GUI parts and simply try and insert a date into the DB (from a console app.). The [tag:swing] tag has been removed. – Andrew Thompson May 27 '21 at 13:56
  • try to check this link on how to use jdatechooser https://stackoverflow.com/questions/23564363/getting-value-from-jdatechooser-and-saving-to-ms-sql-db – Ask Warvin May 27 '21 at 23:26

1 Answers1

0

Using + to place data in an SQL statement is EXTREMELY DANGEROUS. Aside from cross-site scripting, it is one of the greatest sources of hacks and vulnerabilities in software! For a more detailed explanation, search the web for “SQL injection”.

Do not, under any circumstances, place data in an SQL statement using concatenation (using + or StringBuilder or StringBuffer or Formatter or any other similar string construction mechanism).

The only safe way to add user-supplied data to a database statement is with PreparedStatement. The String argument you pass to prepareStatement must not have any data in it. Instead, you place question marks (?) in the String, to act as placeholders for data; then you use the various set* methods of PreparedStatement to replace each question mark with data. This allows the PreparedStatement to guarantee safety.

Instant instant = jDateChooser1.getDate().toInstant();
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();

String sql = "insert into transport(s_id,transport_date) values (?, ?)";
pst = con.prepareStatement(sql);
pst.setString(1, jTextField2.getText());
pst.setObject(2, date);
pst.executeUpdate();
VGR
  • 40,506
  • 4
  • 48
  • 63