日期sql查询,java

Date sql query, java

我正在尝试在SQL中执行查询,其中我需要"今天"的日期,月份和年份。

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

但是Date(Now)不起作用,为了将" actuelle"替换为Date(Now())我尝试了此操作,但是不起作用。 因此,如何在下面的语句中用今天的日期BUT仅在日,月和年中"替换" Date(Now())

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}

谢谢!


除非要使代码易于受到SQL注入攻击的攻击,否则黑客可以窃取您的数据并删除表,请不要使用字符串连接将字符串值插入SQL语句中。

使用PreparedStatement

如果您使用的是Java 8,则使用LocalDate.now()是获取当前日期的最简单方法。

因此,您的代码应类似于以下内容,使用有意义的变量名而不是诸如s6之类的晦涩名称。

当然,您应该针对变量的实际数据类型调整setXxx()调用。

1
2
3
4
5
6
7
8
9
10
11
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();
}

如果不能使用LocalDate,请获取如下的java.sql.Date对象:

1
2
3
4
5
6
7
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());

然后在第一个setter调用中使用它:

1
stmt.setDate(1, today);