Search code examples
javasqleclipseconnectionsqlexception

Connecting a Java application to an SQL database with Eclipse


I know this has been asked before but I really can't get this to work and as far as I can see I've followed all the steps.

I'm using Eclipse.

So I downloaded the Microsoft SQL Driver sqljdbc v4.0. I created a new project and class. I edited the build path by adding the .jar file to the libraries.

I typed the following code:

package com.test.sql;
import java.sql.*;
public class Connect
{
public static void main (String[]args)
{
    Connection con = null;
    String conURL = "jdbc:sqlserver://localhost; databaseName=AnotherTestDB;";
    try
    {
        con = DriverManager.getConnection(conURL);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

}

I got the following error:

java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost; databaseName=AnotherTestDB;
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at com.test.sql.Connect.main(Connect.java:11)

A bit more research and I was told put it in the java /lib/ext and reference it from there.

Nothing changed.

Any help?

Thanks.


Solution

  • Thanks for the responses.

    I had both the sqljdbc4.jar and sqljdbc.jar referenced. The version of Java I am using requires that I use sqljdbc4.jar but it was being overwritten by sqljdbc.jar so I removed it.

    I also changed my code to this:

    public static void main (String[] args)
    {
        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://nameMyLaptop//SQLEXPRESS";
            Connection con = DriverManager.getConnection(connectionUrl);
        }
    
    //Insert catches
    }
    

    Apparently I didn't have to change the code but its not giving me that error now. I'm getting a new one but that's unrelated to my question.

    Thanks for your time and responses.