【问题标题】:doing a look-up and writing a query to get the data from sql server进行查找并编写查询以从 sql server 获取数据
【发布时间】:2012-09-17 08:10:29
【问题描述】:

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

【问题讨论】:

  • 代码应该相同。究竟是什么问题?
  • @JBNizet 如何定义数据源 (jdbc/PollDatasource) ?之前我在 web-app 的 context.xml 中定义
  • 您的意思是问题在于您现在正尝试从桌面应用程序而不是 Web 应用程序访问数据库,并且不知道如何定义数据源,对吧?如果是这样,直接使用DriverManager获取1个连接,或者选择一个连接ppol实现(如C3P0)并阅读说明:mchange.com/projects/c3p0/#using_c3p0

标签: java sql-server database jdbc


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2021-12-07
      • 2019-05-06
      相关资源
      最近更新 更多