?
Solved

Standard JDBC question. Class not found?!

Posted on 2003-02-25
43
Medium Priority
?
411 Views
Last Modified: 2013-11-23
I'm trying to connect an Applet to a MSSQL database, but i get the following error:JavaLangClassNotFoundException:com.microsoft.jdbc.sqlserver.SQLServerDriver

I've downloaded the driver but it does not work!

/*Oppretter database-forbindelse*/
public void DbClient()
{    
username = new String("****");          
password = new String("****");

         
databaseURL = new String("jdbc:microsoft:sqlserver://192.168.123.11:1433;")    
databaseName = new String("192.168.123.11");

// prøver å opprette forbindelse med databasen v h a driveren:
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
con = DriverManager.getConnection(databaseURL,username,password);
}
catch (Exception ex)
{
System.out.println(ex);
}
0
Comment
Question by:RayGun
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 22
  • 16
  • 4
  • +1
43 Comments
 
LVL 2

Expert Comment

by:nir2002
ID: 8015326
Hi,

check if the driver class is in his package:
1) You should have hierarchy of folder and the diver class should be in the proper position

you should have a folder name com and in it you have foler name microsoft and int it a folder name jdbc ... at the end you have the driver.

2) the first folder com should be "known" by the classpath

Best regards
Nir
0
 

Author Comment

by:RayGun
ID: 8015440
I have done this, or at least i think so. I edited autoexec.bat and added path =.;C:\j2sdk1.4.0_03\src\com\microsoft\jdbc. Then I ran autoexec.bat but still I get the same error.
0
 
LVL 2

Expert Comment

by:nir2002
ID: 8015604
It is not the path varibale you need to set, but the classpath variable.

for eg in your bath file:

set CLASSPATH = C:\j2sdk1.4.0_03\src;<put other classes and parent folders of packages and jars your application need directly or undirectly>

java -classpath %CLASSPATH% <execution class>
 
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 2

Expert Comment

by:nir2002
ID: 8015670
If everyelse is set well that will work for stand alone application.

In case of applet you should change your html for downloading a jar that contain your classes and the full packages of driver and put the jar in the http server.

0
 
LVL 2

Expert Comment

by:nir2002
ID: 8015703
this link will help you how to configure your HTML
http://java.sun.com/docs/books/tutorial/applet/appletsonly/html.html

another link you should need to consider if not consider already

http://java.sun.com/docs/books/tutorial/applet/practical/security.html
0
 

Author Comment

by:RayGun
ID: 8015876
As you probably allreaddy have picked up on, I'm relatively new to this. My applet is called ArticleInterface so the execution class is Article Interface.class right?
You also say that I should put the JDBC driver in the HTTP server togheter with the applet class files. Correct?
Then I must also change the CLASSPATH accordingly I presume, but isn't it restricted to my local machine?
0
 

Author Comment

by:RayGun
ID: 8016093
java -classpath %CLASSPATH% <execution class>

When I run autoexec.bat with ArticleInterface.class I get
exception in thread "main" java.lang.NoClassDefFoundError:SQL
0
 

Author Comment

by:RayGun
ID: 8016980
I've made a few changes but it has made little difference.
When I run the applet I get the message:
No suitable drivers. I have set the CLASSPATH to the appropriate driver.class.Here is the code, I hope someone has some advice while I still have hair to pull. Thnx

import java.applet.Applet;
import java.applet.*;
import javax.swing.*;
//import java.awt.Graphics;
//import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.Date;


public class ArticleInterface extends Applet implements ActionListener, ItemListener
{
      //globale variabler UI
      private Button btHeadline;             //Knapp for overskrift
      private Button btPictureText;       //Knapp for bildetekst
      private Button btText;                   //Knapp for tekst
      private Button btSource;            //Knapp for kilde
      private Button btDate;                  //Knapp for dato
      private TextField tfHeadline;       //Artikkelens overskrift
      private TextArea taPictureText; //Bildetekst
      private TextArea taText;             //Artikkelens innhold
      private TextField tfSource;            //Hvor artikkelen er hentet fra
      private String headline;            //string for e lagre innholdet i btHeadline
      private String pictureText;            //string for e lagre innholdet i PictureText
      private String text;                   //string for e lagre innholdet i Text
      private int headlineLength;            //int med lengden av overskrift
      private int pictureTextLength;      //int med lengden av intro
      private int textLength;                  //int med lengden av brxdtekst
      private Button btShow;                  //Knapp for visning av bilde
      private TextField tfFilename;      //adressen til bildet
      private ImageCanvas c;                  //lerretet for visning av bildet
      private Checkbox chkPri;            //setter evt prioritering til 1
      boolean check;

      //Globale variabler JDBC
      String databaseURL, databaseName;
      Connection con;
      public static Statement stmt;
      public static ResultSet rs;
      public static ResultSetMetaData rsmd;

      private String username;
      private String password;

  public void init()
  {
        //setter farger og layout for applet
        setBackground(Color.lightGray);
        setLayout(null);

        //oppretter et grafikkpanel
        Panel p = new Panel();

        //oppretter grafikkobjekter til panelet
        //Tekstdel
        btHeadline = new Button("Skriv Overskrift");
        btPictureText = new Button("Skriv Intro");
        btText = new Button("Skriv Brxdtekst");
        btSource = new Button("Kilde");
        btDate = new Button("Sett dato");
        tfHeadline = new TextField(20);
        tfSource = new TextField(20);
        taPictureText = new TextArea("",5,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
        taText = new TextArea("",5,10,TextArea.SCROLLBARS_VERTICAL_ONLY);
        chkPri = new Checkbox("Prioritert");

        //oppretter fonter
        Font fontHeadLine = new Font("Areal", Font.BOLD, 20);
        Font fontPictureText = new Font("Areal", Font.BOLD, 12);

        //Bildedel
        btShow = new Button("Vis Bilde");
        tfFilename = new TextField(20);
        c = new ImageCanvas();

      //plasserer grafikkobjekter til panelet
        //knapper
        p.add(btHeadline);
        btHeadline.setBounds(50,50,100,30);

        p.add(btPictureText);
        btPictureText.setBounds(50,150,100,30);

        p.add(btText);
        btText.setBounds(50,380,100,30);

        p.add(btSource);
        btSource.setBounds(50,610,100,30);

        //tekstfelt
        p.add(tfHeadline);
        tfHeadline.setBounds(250,50,200,30);
        tfHeadline.setFont(fontHeadLine);

        p.add(taPictureText);
        taPictureText.setBounds(250,150,200,200);
        taPictureText.setFont(fontPictureText);

        p.add(taText);
        taText.setBounds(250,380,200,200);

        p.add(tfSource);
        tfSource.setBounds(250,610,200,30);
        //Bildedel
        p.add(c);
        c.setBackground(Color.gray);
        c.setBounds(600,50,180,200);

        p.add(btShow);
        btShow.setBounds(600,300,100,30);
        p.add(tfFilename);
        tfFilename.setBounds(750,300,200,30);

        p.add(btDate);
        btDate.setBounds(600,360,100,30);
        //Checkboxer
        p.add(chkPri);
        chkPri.setBounds(600,420,100,30);

        //plasserer panelet i framen uten layout
        add(p);
        p.setLayout(null);
        p.setBounds(0,0,1024,768);

        //initialiserer listener
        btHeadline.addActionListener(this);
        btPictureText.addActionListener(this);
        btText.addActionListener(this);
        btShow.addActionListener(this);
        btDate.addActionListener(this);
        tfFilename.addActionListener(this);
        chkPri.addItemListener(this);

        DbClient();

  }


  //ActionEvent handler
  public void actionPerformed(ActionEvent e)
  {
        String actionCommand = e.getActionCommand();
        if ((e.getSource() instanceof Button) || (e.getSource() instanceof TextField))
        {
              if (actionCommand.equals("Skriv Overskrift"))
                {
                  //setter fonter,linjeskift,stxrrelse
                    headline = tfHeadline.getText();
                    headlineLength = headline.length();

              }
              else if (actionCommand.equals("Skriv Bildetekst"))
              {
                       //setter fonter,linjeskift,stxrrelse
                    pictureText = taPictureText.getText();
                    pictureTextLength = pictureText.length();

              }
              else if (actionCommand.equals("Skriv Artikkel"))
              {
                    //setter fonter,linjeskift,stxrrelse
                    text = taText.getText();
                    textLength = text.length();
                  /*  for(int i = 0;i < textLength)
                    {
                    }*/

              }
              else if (actionCommand.equals("Sett dato"))
              {
                    //setter dato
                    Date currentDate = new Date();
                    SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
                    String formatert = fmt.format(currentDate);
                    System.out.println(formatert);
              }

              else if (actionCommand.equals("Vis Bilde") || (e.getSource() instanceof TextField))
              {
                    displayImage();
              }
        }
  }
  public void itemStateChanged(java.awt.event.ItemEvent e)
  {
        if (e.getSource() instanceof Checkbox)
        {

              check = chkPri.getState();      //sjekker om sjekkboks er satt
              if (check = true)
              {
                    System.out.println(check);
              }
        }
  }

  /*Visning av bilde*/
  private void displayImage()
  {
        System.out.println("test");
        //Henter bilde
        Image image = getImage(getCodeBase(), tfFilename.getText().trim());
        //Viser bildet pe lerretet
        c.showImage(image);
  }




      /*Oppretter database-forbindelse*/
      public void DbClient()
      {      username = new String("****");
            password = new String("****");

            databaseURL = new String("jdbc:mysql://server-2:1433;");
            databaseName = new String("server-2");

            // prxver e opprette forbindelse med databasen v h a org-driveren:
            try
            {
                  Class.forName("org.gjt.mm.mysql.Driver");

            }
            catch (ClassNotFoundException ex)
            {
                  System.out.println(ex);
            };
            System.out.println("JDBC driver loaded");
            try
            {
                  con = DriverManager.getConnection(databaseURL);//,username,password);
            }
            catch (java.sql.SQLException ex)
            {
                  System.out.println("Error " + ex.getErrorCode() +ex.getMessage());
                  //System.exit(0);

            };

      }

  }

  //definerer lerrettet for bildevisning
  class ImageCanvas extends Canvas
  {
       private String filename;
       private Image image = null;

       public ImageCanvas()
       {


       }

         //set Image
         public void showImage(Image image)
         {
             //System.out.println("test");
             this.image = image;
             repaint();
       }


       public void paint(Graphics g)
       {
             if (image != null)
                   g.drawImage(image,0,0,getSize().width, getSize().height, this);

       }

  }
0
 
LVL 3

Expert Comment

by:schybert
ID: 8017280
Since you're running it as an applet it doesn't matter what you put into your CLASSPATH...

Are you planning on placing the drivers locally on the users machine or on the web server?
0
 

Author Comment

by:RayGun
ID: 8017321
Doesn't really matter, the applet is only for in house use anyway.
0
 

Author Comment

by:RayGun
ID: 8017351
I'm under the impression that I need to download it from the server though, because of the applet restrictions.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8017362
OK, then I'd suggest just putting the jar file containing the drivers into your <path to java plug-in>/lib/ext folder... That way the java plug-in will find the classes.

(usually something like c:\program\javasoft\jre\1.4\lib\ext if you're on a windows system)
0
 

Author Comment

by:RayGun
ID: 8017476
Ok, it doesn't work yet, but god damn it's a step in the right direction. Still getting the same error though.
0
 

Author Comment

by:RayGun
ID: 8017529
Do I need to tweak the code in Class.forName("org.gjt.mm.mysql.Driver"); to the java plug-in folder as well?
0
 
LVL 1

Expert Comment

by:tutran
ID: 8018229
I don't know what jar files you use.  I had to include a total of 3 jars:

msbase.jar
mssqlserver.jar
msutil.jar

So, make sure that your classpath include these 3 jars or you may run into problems.
0
 

Author Comment

by:RayGun
ID: 8023588
I'm getting confused. Do I need to configure my classpath when I'm using an applet or not.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8023660
No you don't. Just put those 3 jar-files in the directory I pointed out earlier.
0
 

Author Comment

by:RayGun
ID: 8023701
Ok good. I've put the jar-files in this directory C:\j2sdk1.4.0_03\jre\lib\ext.
But I'm afraid I'm still getting the no suitable driver error.
0
 

Author Comment

by:RayGun
ID: 8023748
If all the adjustment I need to do on my system is to allocate these jar-files I guess the error has to be in my code. Don't I need to state somewere in the code were the drivers are located.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8023765
Nope. But I'm pretty sure you have another jre\lib\ext directory under program\javasoft or something like that... that's where you need to put the files.
0
 

Author Comment

by:RayGun
ID: 8023823
Well yes, I have the same directory j2sdk1.4.0_03 in my program files. Tryed putting the files in here with the same results. I'm not finding any javasoft or close variation on my system.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8023829
Put the line
System.out.println(System.getProperty("java.home"));

in the applet's init method to see where java_home is for your plug-in. (You'll have to open the plug-in console to see what it writes out).
0
 

Author Comment

by:RayGun
ID: 8023872
In the console I'm getting access denied when I run with that line.
By the way thnx for the patience, I don't think I am as stupid as it seems but this is getting on my nerves.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8023904
Are you sure the dirver org.gjt.mm.mysql.Driver is included in the jar files you mentioned above?

I know the feeling... och sen är det alltid kul att hjälpa en annan nordbo ;-)
0
 

Author Comment

by:RayGun
ID: 8023982
hehe, godt å høre. Spesielt etter herrestafetten igår.;)
No it doesn't. I've downloaded two drivers:
The org.gjt.mm.mysql.Driver should be part of mysql-connector-java-3.0.6-stable.jar.
The com.microsoft.jdbc.sqlserver.SQLServerDriver should be part of the three .jar files mentioned above.
I'm trying them both as we go. All of the necessary jar files for both drivers have been copied to jre\lib\ext directory.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8024028
Stafett? Den har vi redan glomt ;-) Ser fram emot 5-milen...

Open the java plug-in admin program from the control panel. Under "advanced" you should be able to point the plug-in to the jre where your jar-files are located.
0
 

Author Comment

by:RayGun
ID: 8024101
Ok, done. the plug-in now points to c:\j2sdk1.4.0_03
and the jar files are located in C:\j2sdk1.4.0_03\jre\lib\ext. Still there error 0 no suitable driver.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8024190
Ah, ok. That means the drivers are found, but I guess your jdbc-url is wrong... Are you sure jdbc:mysql://server-2:1433 is correct?
0
 
LVL 3

Expert Comment

by:schybert
ID: 8024202
The fact that you're getting "No suitable driver" implies that the _format_ of the url is incorrect. And btw are you using an MSSQL db or MySql?
0
 

Author Comment

by:RayGun
ID: 8024271
It's a mssql db. I was under the impression that the mysql-connector-java-3.0.6-stable could be used for both mssql and mysql.
The code for the microsoft driver is as follows:
public void DbClient()
     {     username = new String("****");
          password = new String("****");

          databaseURL = new String("jdbc:microsoft:sqlserver://server-2:1433;");
          databaseName = new String("server-2");

          // prøver å opprette forbindelse med databasen v h a org-driveren:
          try
          {
               Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

          }
          catch (ClassNotFoundException ex)
          {
               System.out.println(ex);
          };
          System.out.println("JDBC driver loaded");
          try
          {
               con = DriverManager.getConnection(databaseURL,username,password);
          }
          catch (java.sql.SQLException ex)
          {
               System.out.println("Error " + ex.getErrorCode() +ex.getMessage());
               //System.exit(0);

          };

     }
0
 
LVL 3

Expert Comment

by:schybert
ID: 8024379
OK, I've never used it so you can probably use any of them... I think I've found the problem though. The url string ends with a semicolon. Try removing that.
Change:
"jdbc:microsoft:sqlserver://server-2:1433;"
To:
"jdbc:microsoft:sqlserver://server-2:1433"
0
 

Author Comment

by:RayGun
ID: 8024469
Oh, man I thought you had it! But alas, still no luck. I need to go out on asignment. But if you come up with anything else i'd appreciate it very much and test it later.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8024894
So you get the same error? No suitable driver...
0
 

Author Comment

by:RayGun
ID: 8026115
That's correct. No suitable driver.
0
 
LVL 3

Expert Comment

by:schybert
ID: 8031692
Since the drivers obviously get loaded all I can think of is that you get the "No suitable driver" message because there's something wrong with the format of the jdbc URL. But I can't see what... it looks OK to me...

I would try writing a simple test as an application that just tries to get a connection to the DB. Something like:

import java.sql.*;

public class DBTest {
  public static void main(String[] args) throws Exception {
    String dbURL = "jdbc:microsoft:sqlserver://server-2:1433";
    String username = "****";
    String passwd = "****";
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    Connection c = DriverManager.getConnection(dbURL, username, passwd);
    System.out.println("Whooopeee it worked");
    c.close();
  }
}
     
0
 

Author Comment

by:RayGun
ID: 8031892
ok, I tried it but it didn't work either. Did get a different error though.[driver]Login failed for user '****' at etc. And after that I get at lot of unknown source errors. Could it be that some setting on the db is set wrong? Could I get 'no suitable driver' if the login or password is wrong.  
0
 
LVL 3

Expert Comment

by:schybert
ID: 8032327
Hmmm... the error with the application is obviously related to wrong username. But I don't think you could get a No suitable driver error due to that.
0
 

Author Comment

by:RayGun
ID: 8032484
The snippet you sent me should defenetly work if the the login and pass I've been given gives me the necessary permissions so I've told the system guys to look into it and decided to convert my applet to an application.
It seems easier to run JDBC with apps because of the applet restrictions.
I've done the necessary changes to the code and it compiles fine but I get an error when I run it in thread "main" NoClassDefFoundError. Ring any bells? PS: I will raise the points because of your incredible patience.
0
 
LVL 3

Accepted Solution

by:
schybert earned 120 total points
ID: 8040048
Yeah, I forgot to mention that you have to add the jar-filers to your classpath if you're running it as an application. Just doing this would do the trick:

java -classpath ./msbase.jar;./msutil.jar;./mssqlserver.jar;. ArticleInterface
0
 

Author Comment

by:RayGun
ID: 8040265
I think I may be messing up where I add these files.
In sysedit->autoexec.bat I've added:
set CLASSPATH=C:\Program Files\Java\j2re1.4.0_03\lib\ext\msutil.jar;C:\Program Files\Java\j2re1.4.0_03\lib\ext\mssql.jar;C:\Program Files\Java\j2re1.4.0_03\lib\ext\msbase.jar; and PATH C:\Program Files\Java\j2re1.4.0_03\bin
And I've also added the same thing to system->enviroment variables. I'm pretty sure they do the same thing. So does one override the other?
And last where the do
java -classpath ./msbase.jar;./msutil.jar;./mssqlserver.jar;. ArticleInterface go?
0
 
LVL 3

Expert Comment

by:schybert
ID: 8040514
If you run the line I suggested from the commandline with the jar-files and your class in the current directory you wouldn't need anything of what you've set above. I'd suggest you remove the stuff you put into autoexec.bat at least. It shouldn't cause any problems, but it's unnecessary.
0
 

Author Comment

by:RayGun
ID: 8040815
In fact the statements in my autoexec.bat file was a problem. At least it worked when I removed my statements from it. Your help has been excellent to say the least.
You have surely guided me through the basic concept of JDBC my swedish friend. Thnx
0
 
LVL 3

Expert Comment

by:schybert
ID: 8040832
Hehe, glad to hear that it worked out for you :-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses
Course of the Month7 days, 23 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question