Class forname driver in java

Класс DriverManager

Класс DriverManager является уровнем управления JDBC, отслеживает все доступные драйверы и управляет установлением соединений между БД и соответствующим драйвером.

Прежде чем подключаться к серверу БД необходимо определиться с соответствующим драйвером JDBC, который представляет собой *.jar файл. В следующей таблице представлен список jdbc.drivers для нескольких СУБД.

СУБД Драйвер JDBC Сайт производителя
Oracle oracle.jdbc.OracleDriver http://www.oracle.com/technetwork/database/jdbc-112010-090769.html
MSSQL com.microsoft.jdbc.sqlserver.SQLServerDriver http://www.microsoft.com/en-us/download
PostgreSQL org.postgresql.Driver https://jdbc.postgresql.org/download.html
MySQL com.mysql.jdbc.Driver http://dev.mysql.com/downloads/connector/j/
Derby org.apache.derby.jdbc.ClientDriver http://db.apache.org/derby/derby_downloads.html

Примечание :
1. Драйверы лучше всего скачивать с сайта производителей СУБД.
2. Необходимо учитывать особенности использования подключения к серверу СУБД. Например, если использовать БД Derby в монопольном режиме, т.е. как хранилище, то лучше подключать драйвер org.apache.derby.jdbc.EmbeddedDriver.

Для подключения драйвера лучше всего разместить его в одной из поддиректорией приложения и прописать в classpath. При использовании IDE для разработки приложения подключение драйвера JDBC можно выполнить через интерфейс среды разработки.

Загрузка драйвера JDBC

DriverManager.registerDriver

Чтобы сказать диспетчеру драйверов JDBC, какой именно драйвер следует загрузить, необходимо выполнить одну из команд :

  1. Class.forName(“полное имя класса”)
  2. Class.forName(“полное имя класса”).newInstance()
  3. DriverManager.registerDriver(new “полное имя класса”)

Команды все равнозначны. Задача заключается в том, чтобы classloader загрузил нужный драйвер. Например :

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

Загрузка драйвера JDBC может производиться и другим способом. При вызове Java машины (JVM) можно указать в значении специального системного свойства jdbc.drivers название класса JDBC драйвера:

java -Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver myClass

В этом случае при первой попытке установления соединения с базой данных менеджер драйверов автоматически сам загрузит класс указанный в системном свойстве jdbc.drivers.

Читайте также:  Python telegram bot conversation handler

Выбирайте любой способ, ориентируясь на то, нужно ли вам будет в дальнейшем переходить на другую СУБД. Если да, то, второй способ будет предпочтительнее. Особенно для тех, кто пишет программы для широкой публики. А ей свойственно желать самолй выбирать, чем пользоваться.

Примечание : если при выполнении программы вы получаете ошибку No driver available — это, скорее всего, означает, что вы просто неправильно указалт путь к драйверу в переменной CLASSPATH.

Классы драйверов JDBC разрабатываются со статической секцией инициализации, в которой экземпляр определенного класса создается и регистрируется в классе DriverManager при загрузке. Таким образом, приложение может не вызывать DriverManager.registerDriver непосредственно. Этот вызов автоматически делается самим драйвером при загрузке класса драйвера.

Для обеспечения безопасности управления драйвером JDBC DriverManager отслеживает, каким загрузчиком классов ClassLoader загружен драйвер. При открытии соединения с сервером БД используется только драйвер, поступивший либо из локальной файловой системы, либо загруженные тем же ClassLoader’ом, которым загружено приложение, запросившее соединение с БД.

Соединение с сервером БД

DriverManager.getConnection

Устанавливать соединения с БД можно сразу после регистрации драйвера JDBC. Для этого следует вызвать метод DriverManager.getConnection, которому передаются параметры соединения с БД. DriverManager опрашивает каждый зарегистрированный драйвер с целью определения, какой из них может установить данное соединение. Может оказаться, что установить соединение согласно параметрам URL могут более одного драйвера JDBC. В этом случае важен порядок, в котором происходит этот опрос, так как DriverManager будет использовать первый драйвер, откликнувшийся на URL.

Мост JDBC-ODBC-Bridge

Получить доступ к серверу базы данных можно с использованием моста JDBC — ODBC. Программа взаимодействия между драйвером JDBC и ODBC была разработана фирмой JavaSoft в сотрудничестве с InterSolv. Данная «связка» реализована в виде класса JdbcOdbc.class (для платформы Windows JdbcOdbc.dll).

При использовании JDBC — ODBC необходимо принимать во внимание, что помимо JdbcOdbc-библиотек должны существовать специальные драйвера (библиотеки), которые реализуют непосредственный доступ к базам данных через стандартный интерфейс ODBC. Как правило эти библиотеки описываются в файле ODBC.INI.

На внутреннем уровне JDBC-ODBC-Bridge преобразует методы Java в вызовы ODBC и тем самым позволяет использовать любые существующие драйверы ODBC, которых к настоящему времени накоплено в изобилии. Однако, чаще всего, все-таки используется механизм ODBC благодаря его универсальности и доступности.

Особенности использования JDBC-ODBC

JDBC DriverManager является «хребтом» JDBC-архитектуры, и его основная функция очень проста — соединить Java-программу и соответствующий JDBC драйвер и затем «выйти из игры». Структура драйвера ODBC была взята в качестве основы JDBC из-за его популярности среди независимых поставщиков программного обеспечения и пользователей. Но может возникнуть законный вопрос — а зачем вообще нужен JDBC? не легче ли было организовать интерфейсный доступ к ODBC-драйверам непосредственно из Java? Путь через JDBC-ODBC-Bridge, как ни странно, может оказаться гораздо короче. С чем это связано:

  • ODBC основан на C-интерфейсе и его нельзя использовать непосредственно из Java. Вызов из Java C-кода нарушает целостную концепцию Java и пробивает брешь в защите.
  • Так как Java не имеет указателей, а ODBC их использует, то перенос ODBC C-API в Java-API нежелателен.
  • Java-API необходим, чтобы добиться абсолютно чистых Java решений. Когда ODBC используется, то ODBC-драйвер и ODBC менеджер должны быть инсталлированы на каждой клиентской машине. В то же время, JDBC драйвер написан полностью на Java и может быть легко переносим на любые платформы.

Следующий код демонстрирует соединение с сервером БД с использованием моста jdbc-odbc-bridge :

import java.net.URL; import java.sql.*; import java.io.*; class SimpleSelect < public static void main (String args[]) < String url = "jdbc:odbc:dBase"; String query = "SELECT * FROM users"; try < // Загрузка jdbc-odbc-bridge драйвера Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); DriverManager.setLogStream(System.out); // Попытка соединения с драйвером. Каждый из // зарегистрированных драйверов будет загружаться, пока // не будет найден тот, который сможет обработать этот URL Connection con = DriverManager.getConnection (url, "username", "password"); // Если соединиться не удалось, то произойдет exception (исключительная ситуация). // Получить DatabaseMetaData объект и показать информацию о соединении DatabaseMetaData dma = con.getMetaData (); // Печать сообщения об успешном соединении System.out.println("\nConnected to " + dma.getURL()); System.out.println("Driver " + dma.getDriverName()); System.out.println("Version " + dma.getDriverVersion()); // Закрыть соединение con.close(); >catch (SQLException e) < System.out.println ("\n*** SQLException caught ***\n"); while (e != null) < System.out.println ("SQLState: " + e.getSQLState ()); System.out.println ("Message: " + e.getMessage ()); System.out.println ("Vendor: " + e.getErrorCode ()); e = e.getNextException (); >> catch (java.lang.Exception ex) < e.printStackTrace (); >>

В случае применения моста jdbc-odbc-bridge в URL-строку подставляется DSN (Data Source Name), т.е. имя ODBC-источника из ODBC.INI файла.

Пример динамической загрузки JDBC-драйвера рассмотрен здесь.

Источник

Interface Driver

The Java SQL framework allows for multiple database drivers.

Each driver should supply a class that implements the Driver interface.

The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.

It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast quantities of supporting code.

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling:

A JDBC driver may create a DriverAction implementation in order to receive notifications when DriverManager.deregisterDriver(java.sql.Driver) has been called.

Method Summary

Method Details

connect

Attempts to make a database connection to the given URL. The driver should return «null» if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn. The driver should throw an SQLException if it is the right driver to connect to the given URL but has trouble connecting to the database. The Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. Normally at least «user» and «password» properties should be included in the Properties object. Note: If a property is specified as part of the url and is also specified in the Properties object, it is implementation-defined as to which value will take precedence. For maximum portability, an application should only specify a property once.

acceptsURL

Retrieves whether the driver thinks that it can open a connection to the given URL. Typically drivers will return true if they understand the sub-protocol specified in the URL and false if they do not.

getPropertyInfo

Gets information about the possible properties for this driver. The getPropertyInfo method is intended to allow a generic GUI tool to discover what properties it should prompt a human for in order to get enough information to connect to a database. Note that depending on the values the human has supplied so far, additional values may become necessary, so it may be necessary to iterate though several calls to the getPropertyInfo method.

getMajorVersion

getMinorVersion

jdbcCompliant

Reports whether this driver is a genuine JDBC Compliant driver. A driver may only report true here if it passes the JDBC compliance tests; otherwise it is required to return false . JDBC compliance requires full support for the JDBC API and full support for SQL 92 Entry Level. It is expected that JDBC compliant drivers will be available for all the major commercial databases. This method is not intended to encourage the development of non-JDBC compliant drivers, but is a recognition of the fact that some vendors are interested in using the JDBC API and framework for lightweight databases that do not support full database functionality, or for special databases such as document information retrieval where a SQL implementation may not be feasible.

getParentLogger

Return the parent Logger of all the Loggers used by this driver. This should be the Logger farthest from the root Logger that is still an ancestor of all of the Loggers used by this driver. Configuring this Logger will affect all of the log messages generated by the driver. In the worst case, this may be the root Logger.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

What Is a Driver Class in Java

What Is a Driver Class in Java

This tutorial introduces what is driver class in Java and how to use it in Java, and lists some example codes to understand the topic.

Driver classes are the utility classes that are used to carry out some task. In Java, driver classes are used in JDBC to connect a Java application to a database. Driver classes are vendor-specific i. e. MySQL database provides its own driver class, and Oracle database provides its own class as well.

So, if we want to connect a Java application with a MySQL database, we need to use the driver class provided by MySQL, and we will have to do the same for other databases as well.

To get driver class, we can refer to the official site and then download JARs. Later we can use these JARs in our Java application to connect the application with the database. For example, the OracleDriver class is used for the Oracle database and the Driver class for MySQL.

oracle.jdbc.driver.OracleDriver 

After getting the JARs, to load the Driver class in the Java application, Java provides a Class class that has a forName() method. This method is used to load the driver class.

The Class.forName() method is used to load the class for connectivity.

Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("com.mysql.jdbc.Driver"); 

MySQL Driver Class Example in Java

In this example, we used com.mysql.jdbc.Driver class to connect to the MySQL database. We used JDBC API and its other class, such as DriverManager , to establish the connection.

import java.sql.*; public class SimpleTesting  public static void main(String args[])  try  Class.forName("com.mysql.jdbc.Driver");  Connection con = DriverManager.getConnection(  "jdbc:mysql://localhost:3306/dbname","username","userpassword");  Statement stmt = con.createStatement();  ResultSet rs = stmt.executeQuery("select * from mytable");  while(rs.next())  System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));  con.close();  >catch(Exception e)  System.out.println(e);  >  > > 

Источник

Оцените статью