gpt4 book ai didi

java - JDBC:提示无效符号,但看起来不错

转载 作者:行者123 更新时间:2023-11-30 05:08:00 25 4
gpt4 key购买 nike

我必须使用 JDBC 写入数据库(hibernate/ibatis 不是一个选项),我的数据库是 Oracle 11g。

我创建以下查询: insert into user(user_id, username, Age, Creation_ts) Values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46' ,'DD/MM/RR HH24/MI/SS'));

但是我的statetement.execeuteUpdate(above sql)。生成无效符号异常。但是当我在 squirrel 中执行查询时,它会很好地提交。有谁知道为什么会发生这种情况?

<小时/>
Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
{
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
String url = "privatized";
Connection conn = DriverManager.getConnection(url, "username", "password");

Statement st = conn.createStatement();

Format formatter = new SimpleDateFormat(dateTimeFormatString);
String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
insertQuery.append(username);
insertQuery.append(",");
insertQuery.append(age);
insertQuery.append(",TO_TIMESTAMP('");
insertQuery.append(formattedDate);
insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
System.err.println(insertQuery.toString());
st.executeUpdate(insertQuery.toString());

conn.close();
} catch (SQLException ex){
System.err.println(ex.getMessage());
System.err.println(ex.getCause().toString());
ex.printStackTrace();
System.out.println("=========================================");
} catch(Exception ex) {
System.err.println(ex.getMessage());
}

最佳答案

正如我在上面的评论中所说,问题可能是由于 SQL 语句末尾的额外分号造成的。看到这个article

您可能还想查看PreparedStatments让您的生活更轻松。这是上面代码的粗略翻译。我留下了一些部分,很可能有错误。

String query = "insert into user(user_id, username, age, creation_ts) values(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(query);
... //fill in all your parameters
pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()) );
... //execute here

关于java - JDBC:提示无效符号,但看起来不错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440022/

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