[java] Java program to connect to Sql Server and running the sample query From Eclipse

package sqlselection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Sqlselection 
    {
        public static void main(String[] args)
        {
            try
            {
                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

                String userName = "sa";
                String password = "password";
                String url = "jdbc:microsoft:sqlserver://localhost:1433"+";databaseName=AdventureWorks2008R2";
                Connection con = DriverManager.getConnection(url, userName, password);
                Statement s1 = con.createStatement();
                ResultSet rs = s1.executeQuery("SELECT TOP 1 * FROM HumanResources.Employee");
                String[] result = new String[20];
                if(rs!=null){
                    while (rs.next()){
                        for(int i = 0; i <result.length ;i++)
                        {
                            for(int j = 0; j <result.length;j++)
                            {
                                result[j]=rs.getString(i);
                            System.out.println(result[j]);
                        }
                        }
                    }
                }

                //String result = new result[20];

            } catch (Exception e)
            {
                e.printStackTrace();
            }
    }


}

    enter code here

The Above is my sample program to connect to the Sql server to run the sample select query from eclipse.

I am getting the below error.

java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at sqlselection.Sqlselection.main(Sqlselection.java:13)

i have added the sqljdbc.jar,sqljdbc4.jar to the library. Help to fix this

This question is related to java eclipse jdbc jdbc-odbc

The answer is


download Microsoft JDBC Driver 4.0 for SQL Server which supports:

    SQL Server versions: 2005, 2008, 2008 R2, and 2012.
    JDK version: 5.0 and 6.0.

Run the downloaded program sqljdbc__.exe. It will extract the files into a specified directory (default is Microsoft JDBC Driver 4.0 for SQL Server). You will find two jar files sqljdbc.jar (for JDBC 3.0) and sqljdbc4.jar (for JDBC 4.0), plus some .dll files and HTML help files.

Place the sqljdbc4.jar file under your application’s classpath if you are using JDK 4.0 or sqljdbc4.1.jar file if you are using JDK 6.0 or later.


Right click your project--->Build path---->configure Build path----> Libraries Tab--->Add External jars--->(Navigate to the location where you have kept the sql driver jar)--->ok


The link has the driver for sqlserver, download and add it your eclipse buildpath.


Add sqlserver.jar Here is link

As the name suggests ClassNotFoundException in Java is a subclass of java.lang.Exception and Comes when Java Virtual Machine tries to load a particular class and doesn't found the requested class in classpath.

Another important point about this Exception is that, It is a checked Exception and you need to provide explicitly Exception handling while using methods which can possibly throw ClassNotFoundException in java either by using try-catch block or by using throws clause.

Oracle docs

public class ClassNotFoundException
 extends ReflectiveOperationException

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.


Just Change the query like this:

SELECT TOP 1 * FROM [HumanResources].[Employee]

where Employee is your table name and HumanResources is your Schema name if I am not wrong.

Hope your problem will be resolved. :)


you forgotten to add the sqlserver.jar in eclipse external library follow the process to add jar files

  1. Right click on your project.
  2. click buildpath
  3. click configure bulid path
  4. click add external jar and then give the path of jar

Refer the below link.

There are two important changes that you should make

driver name as "com.microsoft.sqlserver.jdbc.SQLServerDriver"

& in URL "jdbc:sqlserver://localhost:1433"+";databaseName=AdventureWorks2008R2"

http://www.programcreek.com/2010/05/java-code-for-connecting-ms-sql-server-by-using-sql-server-authentication/


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

Examples related to jdbc-odbc

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? JDBC ODBC Driver Connection Java program to connect to Sql Server and running the sample query From Eclipse