如何插入日期
我写了一个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;
}
你能不能帮我解决这个问题?
在查询中有三个参数(?
个字符),所以您需要设置多个参数。你只设置其中一个(第三个),所以你需要有
insertQuery.setString(1, "something");
insertQuery.setString(2, "something else");
insertQuery.setString(3, "2.2.2011");
或者其他set*
方法取决于你的数据类型。请参阅http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
正如BalusC所说,要设置日期,最好在PreparedStatement
上使用setDate()
方法。但是,在使用Oracle时,您也可以考虑使用Oracle函数(请参阅http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm),该函数将字符串转换为Oracle日期。例如
"INSERT INTO USERS (LAST_LOGIN) VALUES (?,?,TO_DATE(?, 'D.M.YYYY')) WHERE USERZ ="+ Update_User;
格式字符串是可以改变的,以满足您的需求
值java.sql.SQLException:缺少IN或OUT参数的指数:: 1
你definied 3值占位符(?,?,?)
:
SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?,?,?) WHERE USERZ ="+ Update_User;
但是,你只设置1值而不是3.
insertQuery.setString(3, "2.2.2011");
您需要将(?,?,?)
由(?)
。
SQL_Statement = "INSERT INTO USERS (LAST_LOGIN) VALUES (?) WHERE USERZ ="+ Update_User;
// ...
insertQuery.setString(1, "2.2.2011");
无关到具体的问题,我还建议由另一个占位符替换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()`?
我还建议让LAST_LOGIN
一个DATE
类型,而不是显然是一个VARCHAR
然后setDate()
设置。通过这种方式,您可以更轻松地让数据库在稍后根据日期选择/排序结果。
最后但并非最不重要,请阅读Java Naming Conventions。 PHP风格的方法和变量名称会让Java代码更难读取到普通的Java开发人员。
你不能在一个SQL语句INSERT
一个WHERE
条款。在我看来,您希望为已经在表中的用户设置最后一次登录时间,而不是向表中添加一行。在这种情况下,你需要使用一个UPDATE
语句来代替,像
SQL_Statement = "UPDATE USERS SET LAST_LOGIN = ? WHERE USERZ = ?";
PreparedStatement insertQuery = conn.prepareStatement(SQL_Statement);
insertQuery.setString(1, "2.2.2011");
insertQuery.setString(2, Update_User);
我在与BalusC同意,你也应该传递用户名使用的占位符,而不是它串联到SQL字符串。
但是,我无法确定将日期设置为字符串(2.2.2011
),因为您正在执行此操作。这很大程度上取决于您使用的是哪个数据库。
您使用的数据库是? – 2011-12-16 12:56:08
更重要的是,你会得到什么例外?它们通常包含整个答案。 – BalusC 2011-12-16 12:58:48