Getting jdbc connection in java

Подключение Connection

Для соединения с БД необходимо использовать класс Connection пакета java.sql. После установления соединения можно выполнять различные SQL-запросы и получать результаты их обработки сервером. Приложение может открыть одно или несколько соединений с одной или несколькими различными СУБД.

Открытие соединения, getConnection

Стандартный способ установления соединения — это вызов метода getConnection класса DriverManager. Методу getConnection необходимо передать строку URL (Uniform Resource Locator). Стандарт подключения к серверу базы данных позволяет использовать следующие методы getConnection с параметрами:

getConnection(url); getConnection(url, properties); getConnection(url, username, password);

При использовании первого варианта, все параметры подключения указываются в url.

В следующей таблице представлен JDBC driver и синтаксис строки URL для подключения к СУБД.

СУБД Драйвер JDBC URL
Oracle oracle.jdbc.OracleDriver jdbc:oracle:oci[OCI_VERSION]:@[HOST_NAME]
Oracle oracle.jdbc.OracleDriver jdbc:oracle:thin:@ [HOST_NAME]:[PORT_NUMBER]:[DATABASE_NAME]
MSSQL com.microsoft.jdbc.sqlserver.SQLServerDriver jdbc:microsoft:sqlserver: //[HOST_NAME]:[PORT_NUMBER]
PostgreSQL org.postgresql.Driver jdbc:postgresql: //[HOST_NAME]:[PORT_NUMBER] /[DATABASE_NAME]
MySQL com.mysql.jdbc.Driver jdbc:mysql://[HOST_NAME]:[PORT_NUMBER] /[DATABASE_NAME]

Подключение к СУБД Oracle, jdbc oracle

К серверу БД Oracle можно подключиться как через тонкий клиент, так и через толстый.

Пример подключения через тонкий клиент:

String host = "localhost"; int port = 1521 ; String sid = "SE" ; String user = "SCOTT" ; String pwd = "TIGER" ; try < Class.forName("oracle.jdbc.driver.OracleDriver"); >catch (ClassNotFoundException e) < System.out.println("Oracle JDBC Driver is not found"); e.printStackTrace(); exit (-1); >String url = String.format("jdbc:oracle:thin:@%s:%d:%s", host, port, sid); Connection connection = null; try < connection = DriverManager.getConnection(url, user, pwd); >catch (SQLException e) < System.out.println("Connection Failed : " + e.getMessage()); exit (-1); >if (connection != null) < System.out.println("You made it, take control your database now!"); >else < System.out.println("Failed to make connection!"); >connection.close();

При подключении через толстый клиент, host и port не указываются :

String sid = "SE" ; String user = "SCOTT" ; String pwd = "TIGER" ; . String url = String.format("jdbc:oracle:oci8:@%s", sid); Connection connection = null; try < connection = DriverManager.getConnection(url, user, pwd); >catch (SQLException e) < System.out.println("Connection Failed : " + e.getMessage()); >.

Подключение к СУБД MS SQL, jdbc sql

Строка URL-адреса подключения имеет следующий вид:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
  • jdbc:sqlserver:// — обязательно, подпротокол.
  • serverName — необязательно, адресом сервера, с которым выполняется соединение. Это может быть DNS, IP-адрес, локальный узел или 127.0.0.1 локального компьютера. Имя сервера необходимо указать в коллекции свойств, если оно не указано в URL-адресе соединения.
  • instanceName — необязательно, наименование базы данных сервера, с которым выполняется соединение. Подключение выполняется к базе данных по умолчанию, если не указана другая.
  • portNumber — необязательно, порт, который слушает сервер. Значение по умолчанию — 1433. Если соединение выполняется с портом по умолчанию, то в URL-адресе необязательно указывать порт.
Читайте также:  Проверить если информация php

Дополнительные свойства указывается в формате ключ=значение.

Примеры установления соединения с сервером БД

// Подключение к БД по умолчанию на localhost: jdbc:sqlserver://localhost;user=userName;password=*****; // Подключение к БД по умолчанию наlocalhost со встроенной проверкой безопасности: jdbc:sqlserver://localhost;integratedSecurity=true; // Подключение к именованной БД: jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true; // Подключение к именованной БД с использованием порта по умолчанию: jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks;integratedSecurity=true; // Подключение к именованной БД с указанием настраиваемого имени приложения: jdbc:sqlserver://localhost;databaseName=AdventureWorks;integratedSecurity=true;applicationName=MyApp;

Подключение к СУБД PostgreSQL, jdbc postgresql

Для подключения к серверу БД PostgreSQL необходимо использовать один из следующих URL:

jdbc:postgresql:database jdbc:postgresql://host/database jdbc:postgresql://host:port/database jdbc:postgresql://host:port

host — имя сервера, по умолчанию «localhost».

port — порт, который слушает сервер. По умолчанию используется порт 5432.

database — наименование базы данных. По умолчанию используется база данных postgres.

Примеры jdbc postgresql :

String url1 = "jdbc:postgresql://localhost/test?user=postgres&password=secret&ssl=true"; String url2 = "jdbc:postgresql://localhost/test"; String user = "postgres"; String pwd = "secret"; Properties props = new Properties (); props.setProperty("user" , user ); props.setProperty("password", pwd ); props.setProperty("ssl" ,"true"); Connection connection1 = DriverManager.getConnection(url1); Connection connection2 = DriverManager.getConnection(url2, props); Connection connection3 = DriverManager.getConnection(url2, user, pwd);

Подключение к СУБД MySQL, jdbc mysql

String driver = «com.mysql.jdbc.Driver»; String url = «jdbc:mysql://localhost:3306/»; String dbName = «. «; String userName = «. «; String password = «. «; try < Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url + dbName, userName, password); if (conn != null) System.out.println ("Приложение подключилось к БД !"); else System.out.println ("Приложение НЕ подключилось к БД ?"); conn.close(); >catch (Exception e)

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

Источник

Establishing a Connection

First, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. Typically, a JDBC application connects to a target data source using one of two classes:

  • DriverManager : This fully implemented class connects an application to a data source, which is specified by a database URL. When this class first attempts to establish a connection, it automatically loads any JDBC 4.0 drivers found within the class path. Note that your application must manually load any JDBC drivers prior to version 4.0.
  • DataSource : This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object’s properties are set so that it represents a particular data source. See Connecting with DataSource Objects for more information. For more information about developing applications with the DataSource class, see the latest The Java EE Tutorial.

Note: The samples in this tutorial use the DriverManager class instead of the DataSource class because it is easier to use and the samples do not require the features of the DataSource class.

Читайте также:  Php and xml book

This page covers the following topics:

Using the DriverManager Class

Connecting to your DBMS with the DriverManager class involves calling the method DriverManager.getConnection . The following method, JDBCTutorialUtilities.getConnection , establishes a database connection:

public Connection getConnection() throws SQLException < Connection conn = null; Properties connectionProps = new Properties(); connectionProps.put("user", this.userName); connectionProps.put("password", this.password); if (this.dbms.equals("mysql")) < conn = DriverManager.getConnection( "jdbc:" + this.dbms + "://" + this.serverName + ":" + this.portNumber + "/", connectionProps); >else if (this.dbms.equals("derby")) < conn = DriverManager.getConnection( "jdbc:" + this.dbms + ":" + this.dbName + ";create=true", connectionProps); >System.out.println("Connected to database"); return conn; >

The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. The following are some examples of database URLs:

  1. MySQL: jdbc:mysql://localhost:3306/ , where localhost is the name of the server hosting your database, and 3306 is the port number
  2. Java DB: jdbc:derby:testdb;create=true , where testdb is the name of the database to connect to, and create=true instructs the DBMS to create the database. Note: This URL establishes a database connection with the Java DB Embedded Driver. Java DB also includes a Network Client Driver, which uses a different URL.

This method specifies the user name and password required to access the DBMS with a Properties object.

  • Typically, in the database URL, you also specify the name of an existing database to which you want to connect. For example, the URL jdbc:mysql://localhost:3306/mysql represents the database URL for the MySQL database named mysql . The samples in this tutorial use a URL that does not specify a specific database because the samples create a new database.
  • In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName . This methods required an object of type java.sql.Driver . Each JDBC driver contains one or more classes that implements the interface java.sql.Driver . The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver , and the one for MySQL Connector/J is com.mysql.cj.jdbc.Driver . See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver . Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName .)
Читайте также:  Сочетание клавишей в javascript

The method returns a Connection object, which represents a connection with the DBMS or a specific database. Query the database through this object.

Specifying Database Connection URLs

A database connection URL is a string that your DBMS JDBC driver uses to connect to a database. It can contain information such as where to search for the database, the name of the database to connect to, and configuration properties. The exact syntax of a database connection URL is specified by your DBMS.

Java DB Database Connection URLs

The following is the database connection URL syntax for Java DB:

jdbc:derby:[subsubprotocol:][databaseName][;attribute=value]*
  • subsubprotocol specifies where Java DB should search for the database, either in a directory, in memory, in a class path, or in a JAR file. It is typically omitted.
  • databaseName is the name of the database to connect to.
  • attribute=value represents an optional, semicolon-separated list of attributes. These attributes enable you to instruct Java DB to perform various tasks, including the following:
    • Create the database specified in the connection URL.
    • Encrypt the database specified in the connection URL.
    • Specify directories to store logging and trace information.
    • Specify a user name and password to connect to the database.

    See Java DB Developer’s Guide and Java DB Reference Manual from Java DB Technical Documentation for more information.

    MySQL Connector/J Database URL

    The following is the database connection URL syntax for MySQL Connector/J:

    jdbc:mysql://[host][,failoverhost. ] [:port]/[database] [?propertyName1][=propertyValue1] [&propertyName2][=propertyValue2].
    • host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively.
    • database is the name of the database to connect to. If not specified, a connection is made with no default database.
    • failover is the name of a standby database (MySQL Connector/J supports failover).
    • propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.

    Источник

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