The Artima Developer Community
Sponsored Link

Java Answers Forum
problem with ODBC data source

10 replies on 1 page. Most recent reply: Jul 9, 2002 12:29 AM by May Lay

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 10 replies on 1 page
May Lay

Posts: 7
Nickname: may
Registered: Jul, 2002

problem with ODBC data source Posted: Jul 3, 2002 6:47 PM
Reply to this message Reply
Advertisement
i have to retrieve list of User DSN and System DSN from ODBC data source using java. my OS is Win2k. what should i do now? pls help


Trung

Posts: 9
Nickname: chitrung
Registered: Jun, 2002

Re: problem with ODBC data source Posted: Jul 4, 2002 1:01 AM
Reply to this message Reply
hi,
just make a connection to the ODBC manager and read the data from the database.
to connect to the ODBC you need this simple code.
first you have to import this class :
java.sql.*;
try {
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
     Connection con = DriverManager.getConnection("jdbc:odbc:database");
}Catch (Exception ex) {}


if you have connected to the database you can read the data from the database with this code :
try {
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery("select * from table");
     while(rs.next()) {
          String thedata = rs.getString("columnname");
     }
}catch (Exception exc) {}


hope this help you.

regards,
trung

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 4, 2002 7:15 PM
Reply to this message Reply
Warning: This program will only function on a Windows Platform since ODBC DSN lists are Windows operating system specific.


/* DSN.java
*/

import java.io.*;
import java.util.*;

/** Produces lists of User DSNs and System DSNs.
* Warning: This program will only function on a Windows Platform
* since ODBC DSN lists are Windows operating system specific.
*/
public class DSN{


private String userDSNCommand = "regedit /e "
+ "\"c:\\temp1.reg\" "
+ "\"HKEY_CURRENT_USER\\Software\\ODBC\\ODBC.INI\\ODBC Data Sources\" ";

private String systemDSNCommand = "regedit /e "
+ "\"c:\\temp2.reg\" "
+ "\"HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources\" ";

private boolean debug = false;


/** Instantiates a class and runs the commands passed in the aguments.
*/
public static void main(String[] args){
DSN dsn = new DSN();
Vector userDSNList = dsn.getUserDSNList();
ListIterator userIterator = userDSNList.listIterator();
System.out.println("User DSN List");
while (userIterator.hasNext()){
System.out.println((String)userIterator.next());
}
Vector systemDSNList = dsn.getSystemDSNList();
ListIterator systemIterator = systemDSNList.listIterator();
System.out.println("System DSN List");
while (systemIterator.hasNext()){
System.out.println((String)systemIterator.next());
}
}

public Vector getUserDSNList(){
runCommand(userDSNCommand.split(" "));
Vector dsnList = new Vector();
try{
FileReader fr = new FileReader("c:\\temp1.reg");
BufferedReader br = new BufferedReader(fr);
String lineRead = "";
while ((lineRead = br.readLine()) != null){
if (lineRead.indexOf("=") > 0){
/* Extract the key portion of a string which looks like:
* "Demo"="Microsoft Access Driver (*.mdb)"
* This would extract the string Demo from the above.
*/
String key = lineRead.substring(1,lineRead.indexOf("\"", 1));
dsnList.add(key);
}
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return dsnList;
}

public Vector getSystemDSNList(){
runCommand(systemDSNCommand.split(" "));
Vector dsnList = new Vector();
try{
FileReader fr = new FileReader("c:\\temp2.reg");
BufferedReader br = new BufferedReader(fr);
String lineRead = "";
while ((lineRead = br.readLine()) != null){
if (lineRead.indexOf("=") > 0){
/* Extract the key portion of a string which looks like:
* "Demo"="Microsoft Access Driver (*.mdb)"
* This would extract the string Demo from the above.
*/
String key = lineRead.substring(1,lineRead.indexOf("\"", 1));
dsnList.add(key);
}
}
}catch(FileNotFoundException fnfe){
System.err.println("FileNotFoundException: " + fnfe.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
return dsnList;
}

/** Runs the commands in a process and displays the results.
*/
public void runCommand(String[] args){
int number = args.length;
try{
String[] commands;
String operatingsystem = System.getProperty("os.name");
if (operatingsystem.toLowerCase().indexOf("windows") > 0){
commands = new String[number + 2];
commands[0] = "command.com"; //for Windows 95, 98, ME. etc.
if (operatingsystem.toLowerCase().indexOf("nt") > 0){
commands[0] = "cmd.exe"; //for Windows NT
}
commands[1] = "/c";
for (int i = 0; i < number;i++){
commands[i+2] = args[i];
}
}else{
commands = new String[number];
for (int i = 0; i < number;i++){
commands[i] = args[i];
}
System.err.println("Microsoft Windows required.");
System.exit(1);

}

if (debug) System.out.print("Executing: ");
for (int i = 0; i< commands.length;i++){
if (debug) System.out.print(commands[i] + " ");
}
if (debug) System.out.println();

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(commands);
// Because some native platforms only provide limited buffer size
// for standard input and output streams, failure to promptly write
// the input stream or read the output stream of the subprocess
// may cause the subprocess to block, and even deadlock.
CheckStream csin = new CheckStream(process.getInputStream());
CheckStream cserr = new CheckStream(process.getErrorStream());
csin.start();
cserr.start();

if (debug) System.out.println("Waiting for command process to terminate...");
int done = process.waitFor();
if (done == 0){
if (debug) System.out.println("Process terminated normally.");
}else{
if (debug) System.out.println("Process terminated abnormally.");
}
process.destroy();
if (debug) System.out.println("... Done.");
}catch(InterruptedException ie){
System.err.println("InterruptedException: " + ie.getMessage());
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}

/** Inner class for checking the results if any of an InputStream.
*/
class CheckStream extends Thread{

BufferedReader br;
String lineread = "";

/** Constructor needs an InputStream to form an anonymous
* InputStreamReader which is used to create a BufferedReader
* for reading the stream.
*/
CheckStream(InputStream is){
this.br = new BufferedReader(new InputStreamReader(is));
}

/** Reads the input stream and displays anything returned.
*/
public void run(){
try{
while ((lineread = br.readLine()) != null){
if (debug) System.out.println(lineread);
}
}catch(IOException ioe){
System.err.println("IOException: " + ioe.getMessage());
}
}
}
}

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 4, 2002 7:17 PM
Reply to this message Reply
You can download this code from:

http://www.quantumhyperspace.com/SourceBank/DSN.java

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 4, 2002 11:20 PM
Reply to this message Reply
I originally thought that since this information is available from the ODBC API, there must be a way to access it with JDBC. After looking around, I can't find it. Maybe there is some obscure way to get the info with a special query to some special secret system table name?

If you are going to go the platform specific route, why not use the ODBC API? As distasteful as it is, it is still better than relying on a particular registry entry to be an accurrate or enduring source of information. You can do this either by making a little "proglet" that you call to generate a properties file (or INI file, in the Windows parlance), or you can do it with JNI.

Here is a little sample of the ODBC code that you would use. I'll leave the exercise of adapting it to JNI or dumping to an INI/properties file to the gentlereader.
void ShowDataSources()
{
   const int lenny = 255;
   char text[1024*16] = "Data Sources:\n";
 
   char serverName[lenny+1];
   int  serverNameLength = 0;
   char description[lenny+1];
   int  descriptionLength = 0;
 
   SQLHENV env;
   SQLAllocEnv( &env );
   SQLRETURN sqlRet = 0;
   sqlRet = SQLDataSources( env,
                            SQL_FETCH_FIRST,
                            (SQLCHAR *)serverName, 
                            lenny,  
                            (SQLSMALLINT *)&serverNameLength,                             
                            (SQLCHAR *)description, 
                            lenny, 
                            (SQLSMALLINT *)&descriptionLength );
 
   switch( sqlRet )
   {
      case SQL_SUCCESS:
         strcat( text, "SQL_SUCCESS!\n" );
         break;
      case SQL_SUCCESS_WITH_INFO:
         strcat( text, "SQL_SUCCESS_WITH_INFO!\n" );
         break;
      case SQL_NO_DATA:
         strcat( text, "SQL_NO_DATA!\n" );
         break;
      case SQL_ERROR:
         strcat( text, "SQL_ERROR!\n" );
         break;
      case SQL_INVALID_HANDLE:
         strcat( text, "SQL_INVALID_HANDLE!\n" );
         break;
      default:
         strcat( text, "Unknown return value!\n" );
         break;
   }
 
   while( sqlRet == SQL_SUCCESS || sqlRet == SQL_SUCCESS_WITH_INFO )
   {
      strcat( text, "\nServer Name: " );
      strcat( text, serverName );
      strcat( text, "\nDescription: " );
      strcat( text, description );
 
      sqlRet = SQLDataSources( env, 
                               SQL_FETCH_NEXT, 
                               (SQLCHAR *)serverName, 
                               lenny,  
                               (SQLSMALLINT *)&serverNameLength, 
                               (SQLCHAR *)description,
                               lenny,
                               (SQLSMALLINT *)&descriptionLength );
   }
 
   MessageBox( NULL, text, "ODBC Info", MB_OK );
}

May Lay

Posts: 7
Nickname: may
Registered: Jul, 2002

Re: problem with ODBC data source Posted: Jul 7, 2002 6:37 PM
Reply to this message Reply
thanks guy!
but Bell, i tried to compile the DSN.java program using both jdk1.3 and 1.4, but both give me this error message:
cannot resolve symbol
method split(java.lang.String)
location: runCommand(userDSNCommand.split(" ") );
how can i solve this problem? i need your advice.

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 8, 2002 12:06 PM
Reply to this message Reply
split is a String method in the j2sdk1.4.0 documented as follows:

split

public String[] split(String?regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex
Result

:
{ "boo", "and", "foo" }
o
{ "b", "", ":and:f" }

Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression

May Lay

Posts: 7
Nickname: may
Registered: Jul, 2002

Re: problem with ODBC data source Posted: Jul 8, 2002 7:49 PM
Reply to this message Reply
is it necessary for me to create a file named temp1.reg and temp2.reg under c: ? because the program give me error: Microsoft Windows Required.

Charles Bell

Posts: 519
Nickname: charles
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 8, 2002 9:10 PM
Reply to this message Reply
Your original request indicated that you were running microsoft windows so I assume you really are.

The program creates the temp1.reg and temp2.reg files when it runs the registry export command, writing out the key values to these temporary files. The program then reads the files and processes the string values to determine the dsn values you indicated you wanted.

There are no direct java programming ways to interact with odbc. There never will be because that would be an operating system specific function. This is contrary to the java programming language premise.

You can however write a jni application as pointed out in the above response. That involves writing some c or c++ code and compiling it external to java. Borland has a free c and c++ compiler. gnu also has a free c compiler.

That's as much as I think I can help you with this.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: problem with ODBC data source Posted: Jul 8, 2002 11:52 PM
Reply to this message Reply
What program gives an error that say "Microsoft Windows Required?" This sounds like a hoax (for lack of more scathing excoriation!).

May Lay

Posts: 7
Nickname: may
Registered: Jul, 2002

Re: problem with ODBC data source Posted: Jul 9, 2002 12:29 AM
Reply to this message Reply
now i can get rid of the "Microsoft Windows Required" message, that's because of the command problem. Win2k also using 'cmd.exe' besides WinNT.
below is the temp1.reg file generated by this program>>

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources]
"MS Access Database"="Microsoft Access Driver (*.mdb)"
"Excel Files"="Microsoft Excel Driver (*.xls)"
"Visual FoxPro Database"="Microsoft Visual FoxPro Driver"
"Visual FoxPro Tables"="Microsoft Visual FoxPro Driver"
"dBase Files - Word"="Microsoft dBase VFP Driver (*.dbf)"
"FoxPro Files - Word"="Microsoft FoxPro VFP Driver (*.dbf)"
"dBASE Files"="Microsoft dBase Driver (*.dbf)"
"MagicTSD"="SQL Server"
"CRSS"="SQL Server"
"BPMain"="Microsoft Access Driver (*.mdb)"
"AddressBook"="Microsoft Access Driver (*.mdb)"
Now the problem is using the String.indexof("=") cannot help me to list down those data sources like CRSS, AddressBook. Any idea to capture the name right infront of "="?

Flat View: This topic has 10 replies on 1 page
Topic: JavaScript popup screen Previous Topic   Next Topic Topic: jbuilder and mysql [easy question for data search]

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use