Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

Java Code print to database?

I have a line of code in a Jar file I'm looking at in eclipse.

There is inbound data (resp) that is getting sent to a command prompt screen

String resp = cnx.getRawResponse();
System.out.println(resp);

I need some code (preferably not just a link) that will send the data to a SQL Server 2005 database stored procedure INSTEAD of the window.
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can get the specific SQL Server jdbc driver, or you can just use the jdbcodbc driver which comes with your installation of java.

You can use CallableStatement, or you can use normal jdbc connection calls.

You can call a stored procedure, but the likelihood is high that you just want to get data with straight SQL.

To use the jdbcodbc driver, you'll need to create an ODBC spec on the Windows machine for your SQL Server db.  Call the ODBC "Testdb" .  Then your code would look something like this:

import java.sql.*;

public class DatabaseExample {
  public static void main(String args[]) {
   Connection con = null;
   Statement stmt = null;
   ResultSet rs = null;

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (Exception e) {
      System.out.println("JDBC-ODBC driver failed to load.");
      return;
    }

    try {
      con = DriverManager.getConnection("jdbc:odbc:Testdb", "username", "password");
      stmt = con.createStatement();
      String plainSQL = "Select Id, Name from NameTable";
     rs = stmt.executeQuery(plainSQL);
    while( rs.next() ) {
         String tableId = rs.getString("Id");
    }
    } catch (Exception e) {
      System.out.println(e);
    } finally {
       if( rs != null ) rs.close();  if( stmt != null ) stmt.close();  if( con != null ) con.close();
}
  }
}
@lrbrister - Can you explain how the accepted answer helped you to "send the data to a SQL Server 2005 database stored procedure" when it only deals with how to query data out of a database?
Avatar of Larry Brister

ASKER

mccarl

You're absolutely right.
I clicked on wrong answer by mistake.

What would you like me to do?
No worries then. There should be a "Request Attention" button above, near your original question, where you can send a message to a Moderator. They can easily re-open the question again, so that you can close in the way you intend. :)
Thanks
No worries, glad to help. And thanks for sorting out the points, much appreciated! :)