gpt4 book ai didi

java sql 插入时间戳 java.sql.SQLSyntaxErrorException

转载 作者:搜寻专家 更新时间:2023-10-30 22:07:55 25 4
gpt4 key购买 nike

我正在尝试将 timestamp 插入到我的数据库中,但我一直收到 java.sql.SQLSyntaxErrorException:

这是我的代码

java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
System.out.println(sqlDate);

这里插入和连接到DB

Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1598/VotingDB", "app", "app");
Statement st = conn.createStatement();
String sql = "INSERT INTO VOTES (CANDIDATE_NAME,VOTER_SSN,TIMESTAMP) "
+ "VALUES ('" + Candidate_Name + "','" + ssn + "'," + TimeStamp + ")";

st.executeUpdate(sql);
st.close();
conn.close();
} catch (SQLException ex) {
System.out.println("Connection failed adding vote " + ex);
}

错误

2017-04-09 20:10:02.825 Connection failed adding vote java.sql.SQLSyntaxErrorException: Syntax error: Encountered "20" at line 1, column 94.

最佳答案

你应该像这样把你的时间放在 '' 之间:

"VALUES ('" + Candidate_Name + "','" + ssn + "', ' " + TimeStamp + "')";

但这不够安全,您必须使用 PreparedStatement 来避免任何 SQL 注入(inject)。

例如:

String sql = "INSERT INTO VOTES (CANDIDATE_NAME, VOTER_SSN, TIMESTAMP) VALUES (?, ?, ?)";

try (PreparedStatement stm = connection.prepareStatement(sql)) {

stm.setString(1, Candidate_Name );
stm.setString(2, ssn );
stm.setDate(3, TimeStamp);

stm.executeUpdate();
}

关于java sql 插入时间戳 java.sql.SQLSyntaxErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310202/

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