繁体   English   中英

在SQL数据库中存储时间戳

[英]Storing timestamp in a SQL database

我在将值存储到在Netbeans中创建的sql数据库中遇到问题。

String bladeSerial;
String bladeType;
LocalTime startTime1;

private void startButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                             


    Connection conn = null; 
    Statement st = null;
try {
    conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
     st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
    Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}


        System.out.println ("Successful Connection");


String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
    pstmt.setString(1, bladeSerial);
    pstmt.setString(2, bladeType);
    pstmt.setString(3, String.valueOf(startTime1));
    pstmt.executeUpdate();
} catch (SQLException ex) {
    // Exception handling
    Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}

startTime1变量以HH:mm:ss.SSS格式保存。 运行代码时,出现错误:

java.sql.SQLSyntaxErrorException:语法错误:在第1行第65列遇到“:”。

错误是指当时的冒号,但我不知道该如何解决。

SERIALVARCHAR(5)BLADETYPEVARCHAR(80)STARTT1VARCHAR(12) 所有列都在DATA表中。

请改用PreparedStatement ,然后使用set*方法设置参数:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
String query = "insert into DATA(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepateStatement(query)) {
    pstmt.setString(1, bladeSerial);
    pstmt.setString(2, bladeType);
    pstmt.setString(3, startTime1.format(formatter));
    pstmt.executeUpdate();
} catch (SQLException e) {
    // Exception handling
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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