原始代码如下:
boolean passed = false;
Statement statement = null;
Connection conn = null;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(DBURL, DBUser, DBPassword);
conn.setAutoCommit(false);
statement = conn.createStatement();
statement.executeUpdate("update tableName set value_start_time = TO_TIMESTAMP('01/" + MonthNumber + "/" + Year + " 11:12:13', 'DD/MM/YYYY HH24:MI:SS')");
statement.close();
conn.commit();
conn.close();
}
catch (Exception ex)
{
//Handle Exception
}
上面的代码可以工作…
我将代码重构为:
函数# 1:
public boolean setupDatabaseConnection() throws ClassNotFoundException, SQLException, TestException
{
try
{
Class.forName("org.postgresql.Driver");
dbConnection = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
}
catch(Exception e)
{
//Handle Exception
}
return true;
}
函数# 2:
public boolean UpdateTableInPostgresDB(String MonthNumber, String Year) throws ClassNotFoundException, SQLException, TestException
{
setupDatabaseConnection();
try
{
dbConnection.setAutoCommit(false);
PreparedStatements("Update This Table");
dbPreparedStatement.setString(1, "01/" + MonthNumber + "/" + Year + " 11:12:13");
dbPreparedStatement.setString(2, "DD/MM/YYYY HH24:MI:SS");
dbPreparedStatement.executeUpdate();
dbConnection.commit();
}
catch (Exception e)
{
//Handle Exception
}
return true;
}
函数# 3
public boolean PreparedStatements(String statementToUse) throws ClassNotFoundException, SQLException, TestException
{
try
{
switch(statementToUse.toLowerCase())
{
case "update this table" :
{
dbQuery = "update tableName set value_start_time = TO_TIMESTAMP(?, ?)";
break;
}
}
dbPreparedStatement = dbConnection.prepareStatement(dbQuery);
{
catch (Exception ex)
{
//Handle Exception
}
现在在函数#2中失败了在我需要这样做的那行:
dbPreparedStatement.executeUpdate();
被捕获的异常是:
老实说,我不知道为什么这不起作用。我用同样的预处理语句函数做了很多其他的SQL查询。ERROR: relation "tableName"位置:8
希望您使用的表名在适当的情况下,因为Postgres是大小写敏感的数据库对象,例如。如果你使用"tabeName"<; tableame <;
请确保在表名中包含模式名(如果适用),然后