Java 执行查找并编写查询以从sql server获取数据
在使用Tomcat作为服务器和Derby作为数据库时,我进行了查找并执行了如下查询:Java 执行查找并编写查询以从sql server获取数据,java,sql-server,database,jdbc,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");
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();
现在我正在使用MicrosoftSQLServer2005,必须从java桌面应用程序查询数据库。查询sql server 2005需要做什么?我已经加载了sqlserver jdbc驱动程序并连接到数据库,但我不知道如何从数据库获取数据。现在需要迭代结果集: 结果集实际上是SQL server中光标的包装器。 在这种情况下,您可能只会得到一个结果。
您需要使用java.sql.ResultSet的getter方法之一从查询中检索值,具体取决于查询结果的预期数据类型。作为方法参数,可以使用列的名称作为字符串(“”),也可以使用查询中列的序列号,以1开头。(一个!)在上面的最后一行代码之后尝试以下操作:
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...
}
代码应该是相同的。到底是什么问题?@JBNizet如何定义数据源
(jdbc/PollDatasource)
?我之前在web应用程序的context.xml中定义过,你的意思是,问题是你现在试图从桌面应用程序而不是web应用程序访问DB,但不知道如何定义数据源,对吗?如果是这样,请直接使用DriverManager获得1个连接,或者选择一个连接ppol实现(如C3P0)并阅读说明: