gpt4 book ai didi

java - 在 SQL 数据库中存储时间戳

转载 作者:行者123 更新时间:2023-12-01 18:03:55 24 4
gpt4 key购买 nike

我在将值存储到我在 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: Syntax error: Encountered ":" at line 1, column 65.

错误指的是时间中的冒号,但我不知道如何解决这个问题。

SERIALVARCHAR(5)BLADETYPEVARCHAR(80) STARTT1 是一个 VARCHAR(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
}

关于java - 在 SQL 数据库中存储时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38375238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com