简体   繁体   中英

Date sql query, java

I'm trying to execute a query in SQL where I need the day, month and year of "today".

INSERT INTO Facture (Date_Achat,Remise, Acompte, Mode_De_Paiement, N°Client) VALUES (Date(Now()), "
                +s6+","+ s7 +" ,'"+s8+"' ,"+s1+"); "

However Date(Now) doesn't work and I tried this in order to put "actuelle" in place of Date(Now()) but doesn't work. So, how can I "replace" Date(Now()) in the following statement by today's date BUT only day, month and year?

Date actuelle = new Date();

//String dat = dateFormat.format(actuelle);
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-mm-dd");

Calendar today = Calendar.getInstance();
today.set(Calendar.DAY_OF_MONTH,Calendar.MONTH,Calendar.YEAR);
try {
    actuelle = formatter.parse(today.toString());
}
catch (ParseException ex) {
    Logger.getLogger(CréationFacture.class.getName()).log(Level.SEVERE, null, ex);
}

Thanks!

DO NOT use string concatenation to insert string values into a SQL statement, unless you want to make your code vulnerable to SQL Injection attacks, where hackers can steal your data and delete your tables .

Use a PreparedStatement .


If you're on Java 8, using LocalDate.now() is the easiest way to get today's date.

So, your code should be something like below, using meaningful variable names instead of obscure names like s6 .

You should of course adjust the setXxx() calls for the actual data types of your variables.

String sql = "INSERT INTO Facture" +
            " (Date_Achat, Remise, Acompte, Mode_De_Paiement, N°Client)" +
            " VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setDate  (1, java.sql.Date.valueOf(LocalDate.now()));
    stmt.setInt   (2, remise);
    stmt.setInt   (3, acompte);
    stmt.setString(4, modeDePaiement);
    stmt.setInt   (5, noClient);
    stmt.executeUpdate();
}

If you can't use LocalDate , get a java.sql.Date object like this:

Calendar cal = Calendar.getInstance();
int year  = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day   = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(year, month, day);
java.sql.Date today = new java.sql.Date(cal.getTimeInMillis());

Then use that in the first setter call:

stmt.setDate(1, today);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM