进行查找并编写查询以从sql server获取数据

时间:2012-09-17 08:10:29

标签: java sql-server database jdbc

使用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驱动程序并连接到数据库,但我不知道如何从数据库中获取数据。

2 个答案:

答案 0 :(得分:0)

现在您需要迭代ResultSet:Retrieving and Modifying Values from Result Sets

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

答案 1 :(得分: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...
}