【发布时间】:2017-05-25 03:06:48
【问题描述】:
我正在尝试制作一个可以接受来自客户端的查询、查找匹配记录并返回相关信息的服务器。这里有很多代码,但最相关的部分是方法getProduct(String code)。我包含了尽可能多的连接信息,以防您想查看,但我的测试查询适用于此连接。我的测试查询是:
ResultSet a = statement.executeQuery("SELECT TOP 10 Code, [name in english], NetSalesPrice, PriceList1 FROM [REDACTED]");
class PCServer {
Connection dataConn;
public static void main(String[] args){
new PCServer();
}
public PCServer(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataConn = DriverManager.getConnection([REDACTED]);
System.out.println("REPORT: Connected to Database");
ServerSocket ss = new ServerSocket([REDACTED]);
Socket cs = null;
while(true){
cs = ss.accept();
ThreadServer ts = new ThreadServer(cs, this);
ts.start();
}
}catch(SQLException sqle){
sqle.printStackTrace();
}catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
public String getProduct(String code){
System.out.println("REPORT from PCS.getProduct(): code == "+ code);
String query = "SELECT Code, [name in english], NetSalesPrice, PriceList1 FROM [REDACTED] WHERE Code=";
query = query.concat(code);
System.out.println("REPORT from PCS.getProduct(): Query: "+ query);
String productDescription = code+":Not:Found";
try{
Statement s = dataConn.createStatement();
ResultSet rs = s.executeQuery(query);
if(rs.isBeforeFirst()) {
System.out.println("REPORT from PCS.getProduct(): rs.isBeforeFirst == true");
rs.next(); //This is throwing com.microsoft.sqlserver.jdbc.SQLServerException: Conversion Failed...
productDescription = rs.getString(1) + ":" + rs.getString(2) + ":$" + rs.getString(3);
}
}catch (SQLException sqle){
System.out.println("SQL Server Exception in getProduct(String code)");
sqle.printStackTrace();
}
return productDescription;
}
在创建或访问 ResultSet 时,异常似乎是数据类型错误或 NumberFormatException 的结果。但是,我尝试将代码转换为 int,即使注释掉 productDescription = rs.getString(1) + ":" + rs.getString(2) + ":$" + rs.getString(3); 行,错误仍然存在。我确信rs.next() 正在引发错误。此外,我们知道 rs 不为空,因为我们检查了rs.isBeforeFirst(),如果 ResultSet 为空,它将返回 false。
这是完整的消息
com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the nvarchar value 'NM21' to data type int.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet$FetchBuffer.nextRow(SQLServerResultSet.java:4853)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.fetchBufferNext(SQLServerResultSet.java:1781)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.next(SQLServerResultSet.java:1034)
at PCServer.getProduct(PCServer.java:83)
at PCServer$ThreadServer.run(PCServer.java:128)
我知道这个问题看起来与其他问题相似。关于这个错误还有很多其他帖子,但ResultSet.next()没有一个是抛出的
【问题讨论】:
标签: java mysql sql-server jdbc