以下代码有效 - 表已更新(通过查看代码执行前后的表内容在 SQL 服务器上确认)。
但是,当我在 NetBeans 和命令行中运行程序时,只要执行“ rs = stmt.executeQuery(SQLquery); ”,CATCH 块就会捕获异常。
我知道这一点是因为“ System.out.println("Updated successfully!"); ”就在 CATCH 块之前从未执行过。如果我将它移到“ rs = stmt.executeQuery(SQLquery); ”之后,它也不会执行。
异常错误是:
run:
The statement did not return a result set.
BUILD SUCCESSFUL (total time: 0 seconds)
我无法理解我做错了什么。
我确实尝试使用“ rs = stmt.executeUpdate(SQLquery); ”而不是“ rs = stmt.executeQuery(SQLquery); ”,但是当我将鼠标悬停在NetBeans 上时,此注释带有红色感叹号:
incompatible types
required: ResultSet
found: int
如果我编译它,NetBeans 会吐出:
C:\Java\Example\src\example\Example.java:56: error: incompatible types
rs = stmt.executeUpdate(SQLquery);
^
required: ResultSet
found: int
1 error
嗯。我要疯了!请帮忙!
package example;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Example
{
public static void main(String args[])
{
String host = "jdbc:sqlserver://SERVER1\\Primrose;databaseName=Primrose";
String uName = "sa";
String uPwd = "Pr1m@f@ct";
String SQLquery = "";
int totalFolders = 4;
int getRecId = 0;
String getUser = "";
String getSection = "";
String getKey = "";
String getValue = "";
String getExtraInfo = "";
try
{
Connection con = DriverManager.getConnection(host, uName, uPwd);
Statement stmt = con.createStatement();
SQLquery = "SELECT * FROM _Registry WHERE (Section = 'RecIds' AND Key_ = '_Folders' AND User_ = 'sc_general')";
ResultSet rs = stmt.executeQuery(SQLquery);
while (rs.next())
{
getRecId = rs.getInt("RecId");
getUser = rs.getString("User_");
getSection = rs.getString("Section");
getKey = rs.getString("Key_");
getValue = rs.getString("Value");
getExtraInfo = rs.getString("ExtraInfo");
getValue = getValue.trim(); // Strip trailing spaces from string
int newValue = Integer.parseInt(getValue) + 1; // Convert string to number so I can add it to total folders
newValue = newValue + totalFolders; // Change to total + existing value to write back to dB
getValue = Integer.toString(newValue); // Convert to string as required by the table
}
SQLquery = "UPDATE _Registry SET Value=" + getValue + " WHERE (RecId = 5 AND User_ = 'sc_general' AND Section = 'RecIds' AND Key_ = '_FOLDERS')";
rs = stmt.executeQuery(SQLquery);
rs.updateInt( "RecId", getRecId );
rs.updateString( "User_", getUser );
rs.updateString( "Section", getSection );
rs.updateString( "Key_", getKey );
rs.updateString( "Value", getValue );
rs.updateString( "ExtraInfo", getExtraInfo );
rs.updateRow();
System.out.println("Updated successfully!");
}
catch ( SQLException err )
{
System.out.println( err.getMessage( ) );
}
}
}