问题描述
这是原始代码的样子:
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,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,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();
被捕获的异常是:
错误:关系“tableName”不存在位置:8
老实说,我不知道为什么这行不通。我使用相同的预处理语句函数执行了很多其他 sql 查询。
解决方法
希望您在正确的情况下使用表名,因为 Postgres 对数据库对象区分大小写,例如。如果您使用“tabeName”,则“tablename”是不同的
如果适用,请确保在表名称中包含架构名称