目前我正在编写一个小程序,该程序应该检查文件是否在数据库中,以及它的SHA264是否正确。如果不正确,应在数据库中更新。
我为更新而编写的功能如下:
public static void updateSHA(String TABLE, String shaOLD, String shaNEW)
{
boolean success = false;
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
PreparedStatement prepStatement = null;
String update = "SET SQL_SAFE_UPDATES = 0" + "; \n" // if I remove this line resp. "'SET SQL_SAFE_UPDATES = 0' + '; \n' + " I get another error code, see below
+ "UPDATE " + dbName + "." + TABLE + " SET sha256 = '" + shaNEW + "' WHERE sha256 = '" + shaOLD + "'" + ";";
try
{
con = DBConnection();
con.prepareStatement(update);
statement = con.createStatement();
resultSet = statement.executeQuery(update);
con.commit();
System.out.println("Successfully updated " + shaOLD + " to " + shaNEW + " in " + dbName + "." + TABLE);
success = true;
}
catch (SQLException sqle)
{
System.out.println(update);
System.out.println("Error at updateSHA for " + shaOLD + ": " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
finally
{
if (con != null)
{
try
{
con.close();
}
catch (SQLException sqle)
{
System.out.println("Error at updateSHA for " + shaOLD + " while closing con: " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
}
if (statement != null)
{
try
{
statement.close();
}
catch (SQLException sqle)
{
System.out.println("Error at updateSHA for " + shaOLD + " while closing statement: " + "[" + sqle.getErrorCode() + "] " + sqle.getMessage());
}
}
if (!success)
{
System.exit(-1);
}
}
}
更新查询的示例:
SET SQL_SAFE_UPDATES = 0;
UPDATE databaseName.tableName SET sha256 = '4e89f735c019ab1af439ec6aa23b85b66f2be1a1b15401b2471599d145cfda42' WHERE sha256 = '000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3';
确切的错误是:
Error at updateSHA for 000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3: [1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE databaseName.tableName SET sha256 = '4e89f735c019ab1af439ec6' at line 2
我认为它与" new"有关。 sha应该替换旧的(因为在错误中它看起来像sha被切断或类似的东西)。
如果我在MySQL Workbench中复制并粘贴上述更新查询,我不会收到任何错误,一切正常(条目更新)。
如果我删除了行' SET SQL_SAFE_UPDATES = 0" +&#34 ;; \ n'我收到以下错误代码:
Error at updateSHA for 000c675c73567f4256c7de7ad7c43056d5f002e08c1a5c7b4ff77a4dd8e479a3: [0] Can not issue data manipulation statements with executeQuery().
假设是由于MySQL安全更新模式而发生第二个错误。
所以我的问题:为什么我会得到1064个错误代表。为什么新的sha会被削减?
答案 0 :(得分:1)
您正尝试在一个语句execute中执行两个语句。 JDBC不允许这样做。从技术上讲,MySQL JDBC驱动程序具有允许这种情况的连接属性,但默认情况下它被禁用(因为该行为违反了JDBC规范)。您需要将其拆分为两个查询。但请注意,SQL_SAFE_UPDATES
的默认值已为0。
如果您确实需要将两个查询作为一个语句执行,请参阅Driver/Datasource Class Names, URL Syntax and Configuration Properties for Connector/J中的 allowMultiQueries 。
问题的第二部分(删除SET SQL_SAFE_UPDATES = 0;
后)是您尝试使用executeQuery
执行不生成ResultSet
的语句。这是不允许的。您应该使用executeUpdate
(或execute
)代替。