Ошибка java sql sqlexception

Полный текст вывода в консоль:

com.mysql.cj.jdbc.Driver@6267c3bb
Драйвер успешно зарегистрирован
Соединение не установлено
java.sql.SQLException: No suitable driver found for jdbs:mysql://localhost:3306/mydbtest
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at database.Main.main(Main.java:33)

package database;

import com.mysql.cj.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Main {

    private static final String URL = "jdbs:mysql://localhost:3306/mydbtest";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "12345trip";
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Connection connection = null;

        try {
            Driver driver = new com.mysql.cj.jdbc.Driver();
            DriverManager.registerDriver(driver);

            Class.forName("com.mysql.cj.jdbc.Driver"); //нужен ли он ??

            System.out.println(driver.toString());
            System.out.println("Драйвер успешно зарегистрирован");

        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("Не удалось загрузить класс драйвера");
        }

        try {

            connection = DriverManager.getConnection(URL,
                    USERNAME, PASSWORD);
            System.out.println(connection);

                if(! connection.isClosed()){
                    System.out.println("Соединение установлено");
                }
        }catch (SQLException e){
            System.err.println("Соединение не установлено");
            e.printStackTrace();
        }
        finally {
            if (connection != null) {
                connection.close();
                System.out.println("Соединение закрыто");
            }

        }


    }
}

Stay organized with collections

Save and categorize content based on your preferences.

An exception that provides information on a database access
error or other errors.

Each SQLException provides several kinds of information:

  • a string describing the error. This is used as the Java Exception
    message, available via the method getMesasge.
  • a «SQLstate» string, which follows either the XOPEN SQLstate conventions
    or the SQL:2003 conventions.
    The values of the SQLState string are described in the appropriate spec.
    The DatabaseMetaData method getSQLStateType
    can be used to discover whether the driver returns the XOPEN type or
    the SQL:2003 type.
  • an integer error code that is specific to each vendor. Normally this will
    be the actual error code returned by the underlying database.
  • a chain to a next Exception. This can be used to provide additional
    error information.
  • the causal relationship, if any for this SQLException.

Public Constructor Summary

SQLException(String reason, String SQLState, int vendorCode)

Constructs a SQLException object with a given
reason, SQLState and
vendorCode.

SQLException(String reason, String SQLState)

Constructs a SQLException object with a given
reason and SQLState.

SQLException(String reason)

Constructs a SQLException object with a given
reason.

SQLException()

Constructs a SQLException object.

SQLException(Throwable cause)

Constructs a SQLException object with a given
cause.

SQLException(String reason, Throwable cause)

Constructs a SQLException object with a given
reason and cause.

SQLException(String reason, String sqlState, Throwable cause)

Constructs a SQLException object with a given
reason, SQLState and cause.

SQLException(String reason, String sqlState, int vendorCode, Throwable cause)

Constructs a SQLException object with a given
reason, SQLState, vendorCode
and cause.

Public Method Summary

Inherited Method Summary


From class
java.lang.Object

Object

clone()

Creates and returns a copy of this Object.

boolean

equals(Object obj)

Compares this instance with the specified object and indicates if they
are equal.

void

finalize()

Invoked when the garbage collector has detected that this instance is no longer reachable.

final

Class<?>

getClass()

Returns the unique instance of Class that represents this
object’s class.

int

hashCode()

Returns an integer hash code for this object.

final

void

notify()

Causes a thread which is waiting on this object’s monitor (by means of
calling one of the wait() methods) to be woken up.

final

void

notifyAll()

Causes all threads which are waiting on this object’s monitor (by means
of calling one of the wait() methods) to be woken up.

String

toString()

Returns a string containing a concise, human-readable description of this
object.

final

void

wait(long timeout, int nanos)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
specified timeout expires.

final

void

wait(long timeout)

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object or until the
specified timeout expires.

final

void

wait()

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object.

Public Constructors


public


SQLException
(String reason, String SQLState, int vendorCode)

Constructs a SQLException object with a given
reason, SQLState and
vendorCode.

The cause is not initialized, and may subsequently be
initialized by a call to the
Throwable.initCause(java.lang.Throwable) method.

Parameters
reason a description of the exception
SQLState an XOPEN or SQL:2003 code identifying the exception
vendorCode a database vendor-specific exception code


public


SQLException
(String reason, String SQLState)

Constructs a SQLException object with a given
reason and SQLState.

The cause is not initialized, and may subsequently be
initialized by a call to the
Throwable.initCause(java.lang.Throwable) method. The vendor code
is initialized to 0.

Parameters
reason a description of the exception
SQLState an XOPEN or SQL:2003 code identifying the exception


public


SQLException
(String reason)

Constructs a SQLException object with a given
reason. The SQLState is initialized to
null and the vender code is initialized to 0.

The cause is not initialized, and may subsequently be
initialized by a call to the
Throwable.initCause(java.lang.Throwable) method.

Parameters
reason a description of the exception


public


SQLException
()

Constructs a SQLException object.
The reason, SQLState are initialized
to null and the vendor code is initialized to 0.

The cause is not initialized, and may subsequently be
initialized by a call to the
Throwable.initCause(java.lang.Throwable) method.


public


SQLException
(Throwable cause)

Constructs a SQLException object with a given
cause.
The SQLState is initialized
to null and the vendor code is initialized to 0.
The reason is initialized to null if
cause==null or to cause.toString() if
cause!=null.

Parameters
cause the underlying reason for this SQLException
(which is saved for later retrieval by the getCause() method);
may be null indicating the cause is non-existent or unknown.


public


SQLException
(String reason, Throwable cause)

Constructs a SQLException object with a given
reason and cause.
The SQLState is initialized to null
and the vendor code is initialized to 0.

Parameters
reason a description of the exception.
cause the underlying reason for this SQLException
(which is saved for later retrieval by the getCause() method);
may be null indicating the cause is non-existent or unknown.


public


SQLException
(String reason, String sqlState, Throwable cause)

Constructs a SQLException object with a given
reason, SQLState and cause.
The vendor code is initialized to 0.

Parameters
reason a description of the exception.
sqlState an XOPEN or SQL:2003 code identifying the exception
cause the underlying reason for this SQLException
(which is saved for later retrieval by the
getCause() method); may be null indicating
the cause is non-existent or unknown.


public


SQLException
(String reason, String sqlState, int vendorCode, Throwable cause)

Constructs a SQLException object with a given
reason, SQLState, vendorCode
and cause.

Parameters
reason a description of the exception
sqlState an XOPEN or SQL:2003 code identifying the exception
vendorCode a database vendor-specific exception code
cause the underlying reason for this SQLException
(which is saved for later retrieval by the getCause() method);
may be null indicating the cause is non-existent or unknown.

Public Methods


public

int

getErrorCode
()

Retrieves the vendor-specific exception code
for this SQLException object.

Returns
  • the vendor’s error code


public

SQLException

getNextException
()

Retrieves the exception chained to this
SQLException object by setNextException(SQLException ex).

Returns
  • the next SQLException object in the chain;
    null if there are none


public

String

getSQLState
()

Retrieves the SQLState for this SQLException object.

Returns
  • the SQLState value


public

Iterator<Throwable>

iterator
()

Returns an iterator over the chained SQLExceptions. The iterator will
be used to iterate over each SQLException and its underlying cause
(if any).

Returns
  • an iterator over the chained SQLExceptions and causes in the proper
    order


public

void

setNextException
(SQLException ex)

Adds an SQLException object to the end of the chain.

Parameters
ex the new exception that will be added to the end of
the SQLException chain

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2021-04-08 UTC.

I’m getting this exception when I try to run this program. It’s one of the Microsoft examples. I’ve added the sqljdbc4.jar to the classpath in netbeans for both compile and Run, via the project properties. I also tested that the class could be found by using an import statement below — no error during compile, so it must be finding the jar.

Could it be related to a dll or some sql dll that the sqldbc4.jar references?

This is the exact exception, and below is the exact code, except for password.

Exception:

run:
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost:1433;databaseName=HealthCareDatabase
Error Trace in getConnection() : No suitable driver found for jdbc:microsoft:sqlserver://localhost:1433;databaseName=HealthCareDatabase
Error: No active Connection
    at java.sql.DriverManager.getConnection(DriverManager.java:602)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at javaapplication1.Connect.getConnection(Connect.java:35)
    at javaapplication1.Connect.displayDbProperties(Connect.java:50)
    at javaapplication1.JavaApplication1.main(JavaApplication1.java:23)
BUILD SUCCESSFUL (total time: 1 second)

Code:

 package javaapplication1;
import com.microsoft.sqlserver.jdbc.SQLServerDriver;

import java.*;

public class Connect {

    private java.sql.Connection con = null;
    private final String url = "jdbc:microsoft:sqlserver://";
    private final String serverName = "localhost";
    private final String portNumber = "1433";
    private final String databaseName = "HealthCareDatabase";
    private final String userName = "larry";
    private final String password = "xxxxxxx";

    // Constructor
    public Connect() {
    }

    private String getConnectionUrl() {
        return url + serverName + ":" + portNumber + ";databaseName=" + databaseName ;
    }

    private java.sql.Connection getConnection() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
            if (con != null) {
                System.out.println("Connection Successful!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error Trace in getConnection() : " + e.getMessage());
        }
        return con;
    }

    public void displayDbProperties() {
        java.sql.DatabaseMetaData dm = null;
        java.sql.ResultSet rs = null;
        try {
            con = this.getConnection();
            if (con != null) {
                dm = con.getMetaData();
                System.out.println("Driver Information");
                System.out.println("tDriver Name: " + dm.getDriverName());
                System.out.println("tDriver Version: " + dm.getDriverVersion());
                System.out.println("nDatabase Information ");
                System.out.println("tDatabase Name: " + dm.getDatabaseProductName());
                System.out.println("tDatabase Version: " + dm.getDatabaseProductVersion());
                System.out.println("Avalilable Catalogs ");
                rs = dm.getCatalogs();
                while (rs.next()) {
                    System.out.println("tcatalog: " + rs.getString(1));
                }
                rs.close();
                rs = null;
                closeConnection();
            } else {
                System.out.println("Error: No active Connection");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dm = null;
    }

    private void closeConnection() {
        try {
            if (con != null) {
                con.close();
            }
            con = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        Connect myDbTest = new Connect();
        myDbTest.displayDbProperties();
    }

}

Piyush Mattoo's user avatar

asked Apr 11, 2011 at 4:56

Larry Watanabe's user avatar

Larry WatanabeLarry Watanabe

10.1k9 gold badges42 silver badges46 bronze badges

3

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

answered Apr 11, 2011 at 5:38

Piyush Mattoo's user avatar

Piyush MattooPiyush Mattoo

15.3k6 gold badges47 silver badges56 bronze badges

4

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

answered Aug 31, 2018 at 9:16

Shams's user avatar

1

Following is a simple code to read from SQL database.
Database names is «database1».
Table name is «table1».
It contain two columns «uname» and «pass».
Dont forget to add «sqljdbc4.jar» to your project. Download sqljdbc4.jar

public class NewClass {

    public static void main(String[] args) {

        Connection conn = null;
        String dbName = "database1";
        String serverip="192.168.100.100";
        String serverport="1433";
        String url = "jdbc:sqlserver://"+serverip+"\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
        Statement stmt = null;
        ResultSet result = null;
        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        String databaseUserName = "admin";
        String databasePassword = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
            stmt = conn.createStatement();
            result = null;
            String pa,us;
            result = stmt.executeQuery("select * from table1 ");

            while (result.next()) {
                us=result.getString("uname");
                pa = result.getString("pass");              
                System.out.println(us+"  "+pa);
            }

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

MarAvFe's user avatar

MarAvFe

4384 silver badges15 bronze badges

answered Jun 27, 2012 at 4:44

Fathah Rehman P's user avatar

Fathah Rehman PFathah Rehman P

8,3514 gold badges40 silver badges42 bronze badges

4

I was having the same error, but had a proper connection string. My problem was that the driver was not being used, therefore was optimized out of the compiled war.

Be sure to import the driver:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

And then to force it to be included in the final war, you can do something like this:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

That line is in the original question. This will also work:

SQLServerDriver driver = new SQLServerDriver();

answered Dec 28, 2017 at 16:59

JeffryHouser's user avatar

JeffryHouserJeffryHouser

39.4k4 gold badges37 silver badges59 bronze badges

You can try like below with sqljdbc4-2.0.jar:

 public void getConnection() throws ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        String url = "jdbc:sqlserver://<SERVER_IP>:<PORT_NO>;databaseName=" + DATABASE_NAME;
        Connection conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
        System.out.println("DB Connection started");
        Statement sta = conn.createStatement();
        String Sql = "select * from TABLE_NAME";
        ResultSet rs = sta.executeQuery(Sql);
        while (rs.next()) {
            System.out.println(rs.getString("COLUMN_NAME"));
        }
    }

answered Jul 26, 2017 at 16:10

shivam srivastava's user avatar

Try append the archive .JAR in Libraries Into The NETBEANS Project . Attention: The Project Category must be «Ant»

answered Sep 20, 2022 at 14:43

Ita's user avatar

Понравилась статья? Поделить с друзьями:
  • Ошибка java security cert
  • Ошибка java runtime environment not found
  • Ошибка java net socket timeout
  • Ошибка java lang unsatisfiedlinkerror
  • Ошибка java lang numberformatexception