如何插入日期

Pet*_*zov -2 java date jdbc

我写了一个用于插入当前日期的java代码,但是当我尝试运行它时会发生异常:

public void Session_Table_Update (String Update_User) throws SQLException{
           String  SQL_Statement = null;
           error_Message = null;
            if (ds == null) throw new SQLException( error_Database = "No data source");      
       Connection conn = ds.getConnection();
            if (conn == null) throw new SQLException( error_Database = "No connection");      

       try {
            conn.setAutoCommit(false);
            boolean committed = false;
                try {
                    SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?,?,?) WHERE USERZ ="+ Update_User;

                       PreparedStatement insertQuery = conn.prepareStatement(SQL_Statement);
                       insertQuery.setString(3, "2.2.2011");

                       insertQuery.executeUpdate();                  


                       conn.commit();
                       committed = true;
                 } finally {
                       if (!committed) conn.rollback();
                       }
            }
                finally {               
                conn.close();

                }  

           return;
       }
Run Code Online (Sandbox Code Playgroud)

你能帮我解决这个问题吗?

Bal*_*usC 5

java.sql.SQLException:索引:: 1处缺少IN或OUT参数

您已经确定了3个值占位符(?,?,?):

SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?,?,?) WHERE USERZ ="+ Update_User;
Run Code Online (Sandbox Code Playgroud)

但是,您只设置1个值而不是3个值.

insertQuery.setString(3, "2.2.2011");
Run Code Online (Sandbox Code Playgroud)

您需要替换(?,?,?)(?).

SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?) WHERE USERZ ="+ Update_User;
// ...
insertQuery.setString(1, "2.2.2011");
Run Code Online (Sandbox Code Playgroud)

具体问题无关,我还建议Update_User用另一个占位符替换以避免SQL注入漏洞.

SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?) WHERE USERZ = ?";
// ...
insertQuery.setString(1, "2.2.2011");
insertQuery.setString(2, Update_User); // Or should it be `setLong()`?
Run Code Online (Sandbox Code Playgroud)

我还建议制作LAST_LOGIN一个DATE类型而不是显然是a VARCHAR然后设置它setDate().通过这种方式,您可以更轻松地让DB在以后根据日期选择/排序结果.

最后但并非最不重要的,请阅读Java命名约定.PHP风格的方法和变量名称使您的Java代码更难以读取给普通的Java开发人员.