Java and sql server connection

Building the connection URL

  • jdbc:sqlserver:// (Required) is known as the subprotocol and is constant.
  • serverName (Optional) is the address of the server to connect to. This address can be a DNS or IP address, or it can be localhost or 127.0.0.1 for the local computer. If not specified in the connection URL, the server name must be specified in the properties collection.
  • instanceName (Optional) is the instance to connect to on serverName. If not specified, a connection to the default instance is made.
  • portNumber (Optional) is the port to connect to on serverName. The default is 1433. If you’re using the default, you don’t have to specify the port, nor its preceding ‘:’, in the URL.

Note For optimal connection performance, you should set the portNumber when you connect to a named instance. This will avoid a round trip to the server to determine the port number. If both a portNumber and instanceName are used, the portNumber will take precedence and the instanceName will be ignored.

For security purposes, you should avoid building the connection URLs based on user input. You should only specify the server name and driver in the URL. For user name and password values, use the connection property collections. For more information about security in your JDBC applications, see Securing JDBC driver applications.

Connection properties

For a detailed list of properties that can be set in the connection string, see Setting the connection properties.

Connection examples

Connect to the default database on the local computer by using a user name and password:

Although the previous example uses a username and password in the connection string, you should use integrated security as it is more secure. For more information, see the Connecting with Integrated Authentication section later in this topic.

The following connection string shows an example of how to connect to a SQL Server database using integrated authentication and Kerberos from an application running on any operating system supported by the Microsoft JDBC Driver for SQL Server:

jdbc:sqlserver://;servername=server_name;encrypt=true;integratedSecurity=true;authenticationScheme=JavaKerberos 

Connect to the default database on the local computer by using integrated authentication:

Connect to a named database on a remote server:

Connect on the default port to the remote server:

Connect by specifying a customized application name:

Named and multiple SQL Server instances

SQL Server allows for the installation of multiple database instances per server. Each instance is identified by a specific name. To connect to a named instance of SQL Server, you can either specify the port number of the named instance (preferred), or you can specify the instance name as a JDBC URL property or a datasource property. If no instance name or port number property is specified, a connection to the default instance is created. See the following examples:

To specify a port number, use the following format:

To use a JDBC URL property, use the following format:

Escaping values in the connection URL

You might have to escape certain parts of the connection URL values if the values include special characters like spaces, semicolons, and quotation marks. The JDBC driver supports escaping these characters by enclosing them in braces. For example, escapes a semicolon.

Before version 8.4, escaped values can contain special characters (especially ‘=’, ‘;’, ‘[]’, and space) but can’t contain braces. Values that must be escaped and contain braces should be added to a properties collection.

In version 8.4 and above, escaped values can contain special characters, including braces. However, closing braces must be escaped. For example, with a password of pass»;<>word , a connection string would need to escape the password as follows:

White space inside the braces is literal and not trimmed.

Connecting with integrated authentication On Windows

The JDBC driver supports the use of Type 2 integrated authentication on Windows operating systems by using the integratedSecurity connection string property. To use integrated authentication, copy the mssql-jdbc_auth—.dll file to a directory on the Windows system path on the computer where the JDBC driver is installed.

The mssql-jdbc_auth—.dll files are installed in the following location:

For any operating system supported by the Microsoft JDBC Driver for SQL Server, see Using Kerberos Integrated Authentication to Connect to SQL Server for a description of a feature added in Microsoft JDBC Driver 4.0 for SQL Server that allows an application to connect to a database using integrated authentication with Type 4 Kerberos.

If you are running a 32-bit Java Virtual Machine (JVM), use the mssql-jdbc_auth—.dll file in the x86 folder, even if the operating system is the x64 version. If you are running a 64-bit JVM on a x64 processor, use the mssql-jdbc_auth—.dll file in the x64 folder.

Alternatively you can set the java.library.path system property to specify the directory of the mssql-jdbc_auth—.dll. For example, if the JDBC driver is installed in the default directory, you can specify the location of the DLL by using the following virtual machine (VM) argument when the Java application is started:

-Djava.library.path=C:\Microsoft JDBC Driver 6.4 for SQL Server\sqljdbc_\enu\auth\x86

Connecting with IPv6 addresses

The JDBC driver supports the use of IPv6 addresses with the connection properties collection, and with the serverName connection string property. The initial serverName value, such as jdbc:sqlserver://serverName, isn’t supported for IPv6 addresses in connection strings. Using a name for serverName instead of a raw IPv6 address will work in every case in the connection. The following examples provide more information.

To use the serverName property:

To use the properties collection:

Properties pro = new Properties();

Connection con = DriverManager.getConnection(«jdbc:sqlserver://;encrypt=true;integratedSecurity=true;», pro);

Источник

Шаг 3. Подтверждение концепции: подключение к SQL с помощью Java

Этот пример следует рассматривать только как подтверждение концепции. Пример кода упрощен для ясности и для него не гарантируется соблюдение рекомендаций корпорации Майкрософт.

Шаг 1. Подключение

Используйте класс подключения для подключения к базе данных SQL.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; try (Connection connection = DriverManager.getConnection(connectionUrl);) < // Code here. >// Handle any errors that may have occurred. catch (SQLException e) < e.printStackTrace(); >> > 

Шаг 2. Выполнение запроса

В этом примере следует подключиться к базе данных SQL Azure, выполнить инструкцию SELECT и вернуть выбранные строки.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; ResultSet resultSet = null; try (Connection connection = DriverManager.getConnection(connectionUrl); Statement statement = connection.createStatement();) < // Create and execute a SELECT SQL statement. String selectSql = "SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"; resultSet = statement.executeQuery(selectSql); // Print results from select statement while (resultSet.next()) < System.out.println(resultSet.getString(2) + " " + resultSet.getString(3)); >> catch (SQLException e) < e.printStackTrace(); >> > 

Шаг 3. Вставка строки

В этом примере следует выполнить инструкцию INSERT, передать параметры и извлечь автоматически созданное значение первичного ключа.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES " + "('NewBike', 'BikeNew', 'Blue', 50, 120, '2016-01-01');"; ResultSet resultSet = null; try (Connection connection = DriverManager.getConnection(connectionUrl); PreparedStatement prepsInsertProduct = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);) < prepsInsertProduct.execute(); // Retrieve the generated key from the insert. resultSet = prepsInsertProduct.getGeneratedKeys(); // Print the ID of the inserted row. while (resultSet.next()) < System.out.println("Generated: " + resultSet.getString(1)); >> // Handle any errors that may have occurred. catch (Exception e) < e.printStackTrace(); >> > 

Источник

Работа с подключением

В следующих разделах приведены примеры различных способов соединения с базой данных SQL Server с помощью класса SQLServerConnection драйвера Microsoft JDBC Driver для SQL Server.

При возникновении неполадок с соединением с SQL Server с помощью драйвера JDBC см. раздел Профилактика подключений, где можно найти сведения по их устранению.

Установка подключения с использованием класса DriverManager

Простейший способ соединения с базой данных SQL Server — загрузка драйвера JDBC и вызов метода getConnection класса DriverManager:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://localhost;encrypt=true;database=AdventureWorks;integratedSecurity=true;" Connection con = DriverManager.getConnection(connectionUrl); 

По этой методике подключение к базе данных будет создано с помощью первого доступного драйвера из списка драйверов, способных успешно подсоединиться к данному URL-адресу.

При использовании библиотеки классов sqljdbc4.jar приложениям не обязательно явно регистрировать или загружать драйвер с помощью метода Class.forName. При вызове метода getConnection класса DriverManager подходящий драйвер выбирается из набора зарегистрированных драйверов JDBC. Дополнительные сведения об использовании JDBC см. в разделе «Использование драйвера JDBC».

Установка подключения с использованием класса SQLServerDriver

Если нужно указать конкретный драйвер из списка драйверов для DriverManager, то можно создать подключение к базе данных с помощью метода connect класса SQLServerDriver:

Driver d = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String connectionUrl = "jdbc:sqlserver://localhost;encrypt=true;database=AdventureWorks;integratedSecurity=true;" Connection con = d.connect(connectionUrl, new Properties()); 

Установка подключения с использованием класса SQLServerDataSource

При необходимости создать соединение с помощью класса SQLServerDataSource можно использовать различные методы задания класса, после чего вызывается метод getConnection:

SQLServerDataSource ds = new SQLServerDataSource(); ds.setUser("MyUserName"); ds.setPassword("*****"); ds.setServerName("localhost"); ds.setPortNumber(1433); ds.setDatabaseName("AdventureWorks"); Connection con = ds.getConnection(); 

Установка подключения, предназначенного для конкретного источника данных

Создать подключение к базе данных, целью которого является конкретный источник данных, можно несколькими способами. Каждый способ зависит от свойств, задаваемых с помощью URL-адреса соединения.

Подключиться к экземпляру по умолчанию на удаленном сервере можно следующим образом:

String url = "jdbc:sqlserver://MyServer;encrypt=true;integratedSecurity=true;" 

Подключиться к конкретному порту на сервере можно следующим образом:

String url = "jdbc:sqlserver://MyServer:1533;encrypt=true;integratedSecurity=true;" 

Подключиться к именованному экземпляру на сервере можно следующим образом:

String url = "jdbc:sqlserver://209.196.43.19;encrypt=true;instanceName=INSTANCE1;integratedSecurity=true;" 

Подключиться к конкретной базе данных на сервере можно следующим образом:

String url = "jdbc:sqlserver://172.31.255.255;encrypt=true;database=AdventureWorks;integratedSecurity=true;" 

Дополнительные примеры URL-адресов подключений см. в статье о создании URL-адреса подключения.

Установка подключения с настраиваемым временем сохранения учетных данных

Если приходится подстраиваться под нагрузку сервера или сети, можно создать соединение с заданным временем сохранения учетных данных в секундах:

String url = "jdbc:sqlserver://MyServer;encrypt=true;loginTimeout=90;integratedSecurity=true;" 

Установка подключения с идентификацией на уровне приложения

Если для работы требуется ведение журнала и профилирование, то необходимо идентифицировать соединение по инициировавшему его приложению:

String url = "jdbc:sqlserver://MyServer;encrypt=true;applicationName=MYAPP.EXE;integratedSecurity=true;" 

Закрытие подключения

Подключение к базе данных можно явно закрыть путем вызова метода close класса SQLServerConnection:

Освобождение ресурсов базы данных, используемых объектом SQLServerConnection, или возврат соединения в пул соединений в сценариях с пулами.

Вызов метода close также приведет к откату любой ожидающей выполнения транзакции.

Источник

Шаг 3. Подтверждение концепции: подключение к SQL с помощью Java

Этот пример следует рассматривать только как подтверждение концепции. Пример кода упрощен для ясности и для него не гарантируется соблюдение рекомендаций корпорации Майкрософт.

Шаг 1. Подключение

Используйте класс подключения для подключения к базе данных SQL.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; try (Connection connection = DriverManager.getConnection(connectionUrl);) < // Code here. >// Handle any errors that may have occurred. catch (SQLException e) < e.printStackTrace(); >> > 

Шаг 2. Выполнение запроса

В этом примере следует подключиться к базе данных SQL Azure, выполнить инструкцию SELECT и вернуть выбранные строки.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; ResultSet resultSet = null; try (Connection connection = DriverManager.getConnection(connectionUrl); Statement statement = connection.createStatement();) < // Create and execute a SELECT SQL statement. String selectSql = "SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"; resultSet = statement.executeQuery(selectSql); // Print results from select statement while (resultSet.next()) < System.out.println(resultSet.getString(2) + " " + resultSet.getString(3)); >> catch (SQLException e) < e.printStackTrace(); >> > 

Шаг 3. Вставка строки

В этом примере следует выполнить инструкцию INSERT, передать параметры и извлечь автоматически созданное значение первичного ключа.

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class SQLDatabaseConnection < // Connect to your database. // Replace server name, username, and password with your credentials public static void main(String[] args) < String connectionUrl = "jdbc:sqlserver://yourserver.database.windows.net:1433;" + "database=AdventureWorks;" + "user=yourusername@yourserver;" + "password=yourpassword;" + "encrypt=true;" + "trustServerCertificate=false;" + "loginTimeout=30;"; String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES " + "('NewBike', 'BikeNew', 'Blue', 50, 120, '2016-01-01');"; ResultSet resultSet = null; try (Connection connection = DriverManager.getConnection(connectionUrl); PreparedStatement prepsInsertProduct = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);) < prepsInsertProduct.execute(); // Retrieve the generated key from the insert. resultSet = prepsInsertProduct.getGeneratedKeys(); // Print the ID of the inserted row. while (resultSet.next()) < System.out.println("Generated: " + resultSet.getString(1)); >> // Handle any errors that may have occurred. catch (Exception e) < e.printStackTrace(); >> > 

Источник

Читайте также:  Php получить расширение изображения
Оцените статью