JDBC:抱怨无效符号,但看起来不错

发布于 2024-10-08 04:57:47 字数 1949 浏览 2 评论 0原文

我必须使用 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'));

但是我的statement.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());
        }

I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: 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'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?


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());
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷迭香的记忆 2024-10-15 04:57:47

正如我在上面的评论中所说,问题可能是由于 SQL 语句末尾的额外分号造成的。请参阅这篇文章

您可能还想查看 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

As I put in a comment above, the issue could be due to the extra Semicolon at the end of your SQL statement. see this article

You may also want to look at PreparedStatments to make your life easier. Here would be a rough translation of your above code. I have left some parts, and there are most likely errors.

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
眼眸里的那抹悲凉 2024-10-15 04:57:47
TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS')

您发送 4 位数的年份,但格式字符串定义 2 位数的年份(无世纪)

尝试一下:

insertQuery.append("', 'DD/MM/RRRR HH24/MI/SS'));");
TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS')

You send a 4-digit year but the format string defines a 2-digit year (no century)

Give this a try:

insertQuery.append("', 'DD/MM/RRRR HH24/MI/SS'));");
暗喜 2024-10-15 04:57:47

您确定 username 变量的值是 'Jack' 而不是 Jack 吗? (ORA-00911 错误看起来不像典型的日期格式错误)。

您还应该了解 PreparedStatement。它们更高效、更易于阅读和调试并且不易受到 SQL 注入的影响。

我的 java 有点生疏,但是使用 PreparedStatement 看起来会像这样:

String query = "insert into user(user_id, username, age, creation_ts) values "
              + "(seq_userid.NEXTVAL, ?, ?, ?)";

Statement st = conn.prepareStatement(query);

st.setString(1, username);
st.setInt(2, age);
st.setTimestamp(3, new java.sql.Timestamp(
                          Calendar.getInstance(
                             TimeZone.getDefault()).getTimeMillis()));

st.executeUpdate(insertQuery.toString());

这样您就不需要将日期转换为字符串来让数据库将其转换回来。此外,您可能会发现该声明更易于阅读,并且您永远不必担心用户使用 ' (单引号)命名其帐户 :)

Are you sure the value of the username variable is 'Jack' and not Jack? (the ORA-00911 error doesn't look like a typical date format error).

Also you should learn about PreparedStatement. They are more efficient, easier to read and debug and not susceptible to SQL injection.

My java is a bit rusty, but this would look something like this with a PreparedStatement:

String query = "insert into user(user_id, username, age, creation_ts) values "
              + "(seq_userid.NEXTVAL, ?, ?, ?)";

Statement st = conn.prepareStatement(query);

st.setString(1, username);
st.setInt(2, age);
st.setTimestamp(3, new java.sql.Timestamp(
                          Calendar.getInstance(
                             TimeZone.getDefault()).getTimeMillis()));

st.executeUpdate(insertQuery.toString());

This way you don't need to convert a date to a string to get it converted back by the DB. Also you may find the statement easier to read and you will never have to worry about user's naming their account with a ' (single-quote) :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文