We help IT Professionals succeed at work.

How applet use jdbc,and client no need set odbc?

glchengang
glchengang asked
on
Medium Priority
432 Views
Last Modified: 2010-03-31
I have a Applet,it use jdbc
server database: MS SQL 7.0 (username=sa,password=none)
server odbc:pcamagazine
//------------The code ------------
public ResultSet dbquery(String sql){
 ResultSet rs = null;
 try {
  Class.forName("com.ms.jdbc.odbc.JdbcOdbcDriver");
  Connection con=DriverManager.getConnection("jdbc:odbc:pcamagazine","sa","");
  Statement sm=con.createStatement();
  rs=sm.executeQuery(sql);
 }
 catch(SQLException ex){}
 catch(java.lang.Exception ex){}
 return rs;
}
//-----------end--------------
  This code is no error,But I have a problem that if the client computer had't set ODBC,the data is can't show in Applet,if the client computer set ODBC,All is right.
  Why???I thing it because applet run after down from server,so applet use ODBC of client. is it????
  I find a way from internet that don't need ODBC
//--------------the code ----------------------
public ResultSet dbquery(String sql){
 String url = "jdbc:inetdae:202.103.190.54?sql7=true"; // use your hostname and port number here
 String login = "sa"; // use your login here
 String password =""; // use your password here
 Connection con = null;
 Statement sm = null;
 ResultSet rs = null;
 try {
  Class.forName("com.inet.tds.TdsDriver").newInstance();
  DriverManager.setLoginTimeout(10);
  con = DriverManager.getConnection(url,login,password);
  con.setCatalog( "register");
  sm = con.createStatement();
  rs = sm.executeQuery(sql);
 }
 catch(SQLException ex){}
 catch(java.lang.Exception ex){}
 return rs;
}
//------------------end-----------------------
I had try this way ,But don't success.

  I hope get a way:
(1)Client computer don't need set ODBC or other.
(2)Client only need IE run this applet from internet
 Who can help me and give me some code? thanks
Comment
Watch Question

Commented:
Hi,
We have two types of jdbc-drivers in java.
1)Thick Driver and 2)Thin Driver.

A thick driver can be a jdbc-odbc bridge driver which requires a odbc driver and sun supplied jdbc bridge driver at client machine, or it can be a Type2 driver which requires database client libraries to be installed and configured at client machine.

A thin driver is a pure 100% java driver which does't require any thing at client machine and which directly opens a socket to the remote database.

For APPLETS only thin driver works and it first downloads the thin driver from webserver and opens a socket to the database server.But here the restriction is that both webserver and database server shold be in the same machine.

Hope this helps you to solve the problem.
Regards,
Giri.

Author

Commented:
tygiri:
  Have you example code ? thanks

Commented:
Try running this Code with

appletviewer demo9.html


/**
 *  Applet code
 */


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;


public class demo9 extends Applet
{

    Connection conn;    // the database connection

    // The GUI controls
    Label connUrlLabel;
    Label UserLabel;
      Label PassLabel;

    TextField connUrlField;
      TextField UserField;
      TextField PassField;

    Button connectBtn;
    Label qryStrLabel;
    TextField qryStrField;
    Button execQryBtn;
    Label resultsLabel;
    TextArea resultsArea;

    public void init()
    {
      setLayout(null);
      setSize(600,400);

      connUrlLabel = new Label("Enter Connection URL");
      connUrlLabel.setBounds(0,24,132,24);
      add(connUrlLabel);

      UserLabel = new Label("User");
      UserLabel.setBounds(80,120,50,24);
      add(UserLabel);

      PassLabel = new Label("Password");
      PassLabel.setBounds(220,120,60,24);
      add(PassLabel);


      //connUrlLabel = new Label("Enter Connection URL");
      //connUrlLabel.setBounds(45,24,132,24);
      //add(connUrlLabel);

      connUrlField = new TextField();
      connUrlField.setBounds(160,12,373,38);
      add(connUrlField);

      UserField = new TextField();
      UserField.setBounds(130,120,50,24);
      add(UserField);

      PassField = new TextField();
      PassField.setBounds(300,120,50,24);
      add(PassField);


      connectBtn = new Button("Connect");
      connectBtn.setBounds(528,12,61,36);
      add(connectBtn);

      qryStrLabel = new Label("Enter Query String");
      qryStrLabel.setBounds(0,72,108,24);
      add(qryStrLabel);

      qryStrField = new TextField();
      qryStrField.setBounds(120,60,373,38);
      add(qryStrField);

      execQryBtn = new Button("Execute Query");
      execQryBtn.setBounds(504,60,95,36);
      add(execQryBtn);

      resultsLabel = new Label("Results");
      resultsLabel.setBounds(12,120,84,24);
      add(resultsLabel);

      resultsArea = new TextArea();
      resultsArea.setBounds(12,156,576,228);
      add(resultsArea);

      // Adding actionListeners for button action events
      connectBtn.addActionListener((ActionListener) new BtnActionListener());
      execQryBtn.addActionListener((ActionListener) new BtnActionListener());
    } // end of init method


    private void connectBtnPressed()
    {
      try
          {
          // Get the connection URL string from the connUrlField text-box
          String connUrlStr = connUrlField.getText();
            String User = UserField.getText();
            String Pass = PassField.getText();

          if (connUrlStr != null)
            {
            String ifxDriver = "com.informix.jdbc.IfxDriver";

            // Register the INFORMIX-JDBC driver
            //Driver IfmxDrv = (Driver)
            Class.forName(ifxDriver);//.newInstance();
        System.out.println("Driver Load");

            // Get a connection to the database server
            conn = DriverManager.getConnection(connUrlStr,User,Pass);
            resultsArea.append("\nDriver loaded...and connection established");
            }
          else
            {
            resultsArea.append("\nERROR - Please enter a connection URL!!");
            return;
            }
          }
      catch (SQLException e)
          {
          resultsArea.append("\nCould not connect to the database!!");
          resultsArea.append("\n" + e.getMessage());
            e.printStackTrace();
          }
      catch (Exception e)
          {
          resultsArea.append("\nGeneric Error : ");
          resultsArea.append("\n" + e.getMessage());
          }
    } // end of connectBtnPressed method


    private void execQryBtnPressed()
    {
      try
          {
          // Get the query statement from the qryStrField text-box
          String qryStr = qryStrField.getText();

          if (qryStr != null)
            {
            // Create a Statement object and use it to execute the query
            Statement stmt = conn.createStatement();
            ResultSet queryResults = stmt.executeQuery(qryStr);

            resultsArea.append("\nQuery executed...");

            // Get ResultSetMataData containing the number, types and
            // properties of the columns in the result set
            ResultSetMetaData queryResultsMetaData =
                queryResults.getMetaData();
            int numOfCols = queryResultsMetaData.getColumnCount();

            // Get the values of the result set rows and display them
            // in the qryResultsArea text-area
            while (queryResults.next())
                {
                // A place-holder to hold the data in the current row
                // of the result set
                StringBuffer dataRow = new StringBuffer();

                // Get column data from every column & display it
                for (int i=1; i<=numOfCols; i++)
                  {
                  dataRow.append(queryResults.getString(i));
                  dataRow.append("\t");
                  }
                resultsArea.append("\n" + new String(dataRow));
                }
            }
          else
            {
            resultsArea.append("\nERROR - Please enter a query string!!");
            return;
            }
          }
      catch (Exception e)
          {
          resultsArea.append("\nError in executing the query!!");
          System.out.println("\n" + e.getMessage());
          }
    } // end of execQryBtnPressed method


    // Private inner class implementing the ActionListener interface
    // for the buttons
    private class BtnActionListener implements ActionListener
    {
      // This is the code that will be executed whenever a button is pressed
      public void actionPerformed(ActionEvent evt)
      {
          Object evtObject = evt.getSource();
          if (evtObject == connectBtn)
            connectBtnPressed();
          else if (evtObject == execQryBtn)
            execQryBtnPressed();
      } // end of actionPerformed method
    } // end of inner class BtnActionListener
} // end of class demo9


// HTML Page

<HTML>
<!--***************************************************************************
*
*                            INFORMIX SOFTWARE, INC.
*
*                              PROPRIETARY DATA
*
* THIS DOCUMENT CONTAINS TRADE SECRET DATA WHICH IS THE PROPERTY OF
* INFORMIX SOFTWARE, INC.&nbsp; THIS DOCUMENT IS SUBMITTED TO RECIPIENT
* CONFIDENCE.  INFORMATION CONTAINED HEREIN MAY NOT BE USED, COPIED
* DISCLOSED IN WHOLE OR IN PART EXCEPT AS PERMITTED BY WRITTEN AGREEMENT
* SIGNED BY AN OFFICER OF INFORMIX SOFTWARE, INC.
*
* THIS MATERIAL IS ALSO COPYRIGHTED AS AN UNPUBLISHED WORK UNDER
* SECTIONS 104 AND 408 OF TITLE 17 OF THE UNITED STATES CODE.
* UNAUTHORIZED USE, COPYING OR OTHER REPRODUCTION IS PROHIBITED BY LAW.
*
*
* Title:         demo9.html
*
* Description:   To connect to the database and execute queries from
*                a Java applet
*
***************************************************************************
*-->

<HEAD>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="GENERATOR" CONTENT="Mozilla/4.04 [en] (WinNT; I) [Netscape]">
   <TITLE>demo9 -- Connecting to a database from an applet using JDBC</TITLE>
</HEAD>
<BODY>
<H2>
To run this demo, you must have the ifxjdbc.jar file in the same directory
on the WebServer as the demo9 class file</H2>

<H2>
Run this demo in the following steps -</H2>

<H3>
1. Enter a connection URL in the text-field and press the 'Connect' button</H3>
The connection URL should be of the form -
<BR><FONT COLOR="#993366">jdbc:informix-sqli://&lt;host_name>:&lt;port_number>/ministores:INFORMIXSERVER=&lt;server_name>;user=&lt;user_name>;password=&lt;password></FONT>
<P>
NOTE: If using a 5.x server release, then add the usev5server=1 property setting in the URL
      string.
</P>
<H3>
2. Once the connection has been established, enter a query string in the
text-field and press the 'Execute Query' button.</H3>
<APPLET CODE=demo9.class  ARCHIVE="ifxjdbc.jar" WIDTH=600 HEIGHT=400 ></APPLET>
</BODY>
</HTML>
As for the jdbc driver itself, I've used the i-net UNA driver, available at:

http://www.inetsoftware.de/

with great success.  Not as nice as using the Oracle drivers, but still...

Commented:
You need instal your data base in the same machine where your applet run's

Explore More ContentExplore courses, solutions, and other research materials related to this topic.