0

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.

Now I have a variable var in Java.

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

How would I accomplish this?

9
  • Not clear what you are asking ? Commented Mar 25, 2015 at 13:40
  • Are you asking how to capture the result of your query into a variable? Commented Mar 25, 2015 at 13:42
  • @CoderofCode Essentially, I can run the given query to obtain a specific date in SQL Server. And in SQL, I can run a job created in Java that generates reports. I want to use the value of that query as a variable in Java. Commented Mar 25, 2015 at 13:42
  • @CharlesCaldwell Precisely. Commented Mar 25, 2015 at 13:43
  • So you want to create the variable with the name as result of that query. Commented Mar 25, 2015 at 13:43

2 Answers 2

1

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.

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());
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I guess you are asking how to access the database from java. Java has an API to talk to any database you have a driver for. Its called JDBC.

For SQLServer get the driver from microsoft, or alternatively use jtds (open source). Add the driver into your project and follow a tutorial on JDBC how to use it (e.g. http://docs.oracle.com/javase/tutorial/jdbc/).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.