[英]How do I use an SQL Query Result as the value of a variable in Java?
I have a below query 我有一个下面的查询
SELECT CONVERT(VARCHAR(8),(select TOP 1 LBD=latest_date
FROM some_table
WHERE latest_date < GETDATE()
ORDER BY latest_date DESC), 112) AS [YYYYMMDD]
which will give me a value like 20150324
for example. 例如,这将给我一个像
20150324
这样的值。
Now I have a variable var in Java. 现在,我在Java中有一个变量var。
I want var to equal the result of the query (so today, it would be var = 20150324, and tomorrow it could be something completely different). 我希望var等于查询的结果(所以今天是var = 20150324,明天可能是完全不同的东西)。
How would I accomplish this? 我将如何完成?
I guess you are asking how to access the database from java. 我猜您在问如何从Java访问数据库。 Java has an API to talk to any database you have a driver for.
Java具有一个API,可以与您拥有驱动程序的任何数据库进行通信。 Its called JDBC.
它称为JDBC。
For SQLServer get the driver from microsoft, or alternatively use jtds (open source). 对于SQLServer,请从Microsoft获得驱动程序,或者使用jtds(开源)。 Add the driver into your project and follow a tutorial on JDBC how to use it (eg http://docs.oracle.com/javase/tutorial/jdbc/ ).
将驱动程序添加到您的项目中,并遵循有关JDBC的使用方法的教程(例如, http : //docs.oracle.com/javase/tutorial/jdbc/ )。
Your code would look something like this. 您的代码看起来像这样。 You would need to get the appropriate jdbc driver and configure the url appropriately, but this is a small sample of how you would do it.
您将需要获取适当的jdbc驱动程序并适当配置url,但这只是您如何做的一小部分示例。
import java.sql.*;
class DoQuery {
public static void main (String[] args) {
try {
String url = "jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT CONVERT(VARCHAR(8),(select TOP 1 LBD=latest_date FROM some_table WHERE latest_date < GETDATE() ORDER BY latest_date DESC), 112) AS [YYYYMMDD]");
while ( rs.next() ) {
String myDate = rs.getString("YYYYMMDD");
System.out.println(myDate);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.