我正在使用 java 创建一个非常简单的 Web 服务示例。我有一个变量 num 初始化为 0,但我无法在最后保留它的值。根据我拥有的数据库,它的值应该增加 1。
下面是网络服务操作:
@WebMethod(operationName = "getNewID")
public String getNewID(@WebParam(name = "newID") String txt2)
{
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
int num=0;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:src/java/db/test.sqlite");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT ID FROM LOGINDETAILS where ID = '"+txt2+"'");
while (resultSet.next())
{
//System.out.println("Your ID "+ resultSet.getString("ID"));
num++;
}
}
catch (Exception e)
{
System.out.println("You had an exception");
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if(num==0)
{
return "Your ID does not match";
}
else
{
return "Welcome "+txt2;
}
}
在我得到的输出中
方法返回 java.lang.String :“您的 ID 不匹配”
对于所有情况,只有 if 部分有效,而 else 部分无效。当我在一个类中尝试相同的方法时,它工作正常,但不是在 web 服务操作的情况下
新代码
@WebMethod(operationName = "getNewID")
public String getNewID(@WebParam(name = "newID") String txt2)
{
String str = null;
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
int num=0;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:src/java/db/test.sqlite");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT ID FROM LOGINDETAILS where ID = '"+txt2+"'");
while (resultSet.next())
{
//System.out.println("Your ID "+ resultSet.getString("ID"));
num++;
}
}
catch (Exception e)
{
System.out.println("You had an exception");
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
assert num == 0 || txt2 == null : str = "num "+num+"txt2 "+txt2;
return str;
/*if(num==0)
{
return "Your ID does not match Please Try Again Or if new user then please register";
}
else
{
return "Welcome "+txt2;
}*/
}
结果,我将 str 的值设为 null。
好的,我现在试过了..
@WebMethod(operationName = "getNewID")
public String getNewID(@WebParam(name = "newID") String txt2)
{
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
int num=0;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:src/java/db/test.sqlite");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT ID FROM LOGINDETAILS where ID = '"+txt2+"'");
while (resultSet.next())
{
num++;
}
return resultSet.toString();
}
catch (Exception e)
{
System.out.println("You had an exception");
e.printStackTrace();
return "You had an exception";
}
}
我得到输出
java.lang.String : "You had an exception"
当它在 Web 服务操作之外工作正常时,为什么它在这里显示异常......我该如何纠正它?