2
votes

I have been trying to create a simple database application in JAVA using JDBC. So far all my attempts have been unsuccessful in even loading the driver. Understand that I'm novice in Java and just started learning. Here are my steps:

  1. Start > System > Advanced System properties > Environment Variables: Added CLASSPATH=[path to sqljdbc41.jar]
  2. Added the Driver in the Netbeans enter image description here
  3. Added the following code:

    public class DataSample {
      public static void main(String[] args) throws Exception{
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          Connection cnn=DriverManager.getConnection   ("jdbc:sqlserver://localhost;databaseName=AdventureWorks;");
          Statement st = cnn.createStatement();
          ResultSet rs =st.executeQuery("select * from test");
    

The program always give this exception:

Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver at java.net.URLClassLoader$1.run(URLClassLoader.java:372) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:360) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:260) at datasample.DataSample.main(DataSample.java:21) Java Result: 1

1
Your first screenshot shows how to setup a database driver for use within Netbeans itself (eg to access the database from Netbeans). If you want to use it from an application you develop using Netbeans, you need to add the driver to the classpath (buildpath) of that application. - Mark Rotteveel
Right click on your "Libraries" node of your project and choose "Add JAR/Folder". You need to add the JDBC driver there. More details in the manual: docs.oracle.com/cd/E50453_01/doc.80/e50452/… - a_horse_with_no_name
Again: Step 1 and 2 are configuration of Netbeans itself, not of your Netbeans projects; those settings aren't used when executing an application you developed in Netbeans. - Mark Rotteveel
It works like a breeze ! thanks - Simple Fellow

1 Answers

1
votes

This is with the help from Mark Rotteveel. Here are the steps. maybe someone else is also having a problem in the same area:

  1. Expand the libraries. enter image description here
  2. Right click and choose Add jar Files enter image description here
  3. Add the Sql Server jar file enter image description here
  4. Add the line to load the driver (see the code in question) and provide the connection string.

  5. I removed the CLASSPATH variable and still works.