1

在使用 Tomcat 作为服务器并使用 Derby 作为数据库时,我进行了查找并执行了如下查询:

        Context initContext = new InitialContext();
        Context envContext = (Context)initContext.lookup("java:comp/env");
        DataSource ds = (DataSource)envContext.lookup("jdbc/PollDatasource");
        Connection connection = ds.getConnection();
        // write the query that tells the current weight of actor
        String currentWeightQuery = "SELECT " + justPolled + ",total FROM pollresult";
        PreparedStatement currentWeight = connection.prepareStatement(currentWeightQuery);
        ResultSet cwSet = currentWeight.executeQuery();

现在我使用Microsoft SQL Server 2005并且必须从 java 桌面应用程序查询数据库。我需要做什么来查询 sql server 2005 ?我已经加载了 sqlserver-jdbc 驱动程序并连接到数据库,但我不知道如何从数据库中获取数据。

4

2 回答 2

0

在上面的最后一行代码之后试试这个:

while (cwSet.next()) {
    String string = cwSet.getString(1); // instead of the 1 you can also use the name of the column as a String
    int i = cwSet.getInt("total"); //could also have used getInt(2)
    // etc...
}
于 2012-09-17T10:57:24.777 回答
0

现在您需要迭代 ResultSet:从结果集中检索和修改值

ResultSet 实际上是 SQL Server 中游标的包装器。在这种情况下,您可能只会得到一个结果。您需要使用 java.sql.ResultSet 的一种 getter 方法从查询中检索值,具体取决于查询结果的预期数据类型。作为方法参数,您可以使用列名作为字符串 (""),或者使用查询中列的序列号,从 1 开始。(一个!)

于 2012-09-17T08:33:36.213 回答