Microsoft SQL Server
Run SQL Server in a Docker container, query it with sqlcmd, connect from Java with jTDS, and define a GlassFish connection pool.
3 min readUpdated
Microsoft SQL Server (MSSQL) runs on Linux and is published as a container image, which makes it easy to get a development database without a Windows machine. This note starts SQL Server in Docker, creates a test table with sqlcmd, reads it from Java over JDBC with the jTDS driver, and shows a GlassFish connection pool for the same driver.
Run SQL Server in Docker
SQL Server needs at least 2 GB of memory. Docker Desktop’s default limit is 2 GB, so raise it to 4 GB in Docker Desktop’s resource settings before starting the container.
Pull the image and start a container. Microsoft now publishes the images on its own registry, mcr.microsoft.com; the original 2017 image was microsoft/mssql-server-linux on Docker Hub.
docker pull mcr.microsoft.com/mssql/server:2022-latestdocker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=<YourPassword>' -e 'MSSQL_PID=Developer' \ --cap-add SYS_PTRACE -p 1401:1433 -d mcr.microsoft.com/mssql/server:2022-latestACCEPT_EULA=Yaccepts the licence; the container stops without it.MSSQL_SA_PASSWORDsets the password of theSAlogin. It must meet SQL Server’s complexity rules, or the server does not start.MSSQL_PID=Developerselects the free Developer edition.--cap-add SYS_PTRACEis only needed for SQL Server’s crash dump collection when troubleshooting; Microsoft’s quickstart runs without it.-p 1401:1433publishes the server’s port 1433 on port 1401 of the host.
Find the container ID and open a shell in it:
docker ps -adocker exec -it <container-id> bashCreate a test database with sqlcmd
Start sqlcmd inside the container. Current SQL Server 2022 and 2019 images ship the tools in /opt/mssql-tools18/bin; older images use /opt/mssql-tools/bin.
/opt/mssql-tools18/bin/sqlcmd -S localhost -U SA -P '<YourPassword>'Version 18 of sqlcmd encrypts the connection by default. If it fails because the server has a self-signed certificate, add -C to trust that certificate, or -No to make encryption optional.
At the sqlcmd prompt, create a database and a table, insert two rows and query them. GO sends the batch to the server and QUIT leaves sqlcmd.
CREATE DATABASE TestDB;USE TestDB;CREATE TABLE Inventory (id INT, name NVARCHAR(50), quantity INT);INSERT INTO Inventory VALUES (1, 'banana', 150);INSERT INTO Inventory VALUES (2, 'orange', 154);SELECT * FROM Inventory WHERE quantity > 152;GOQUITConnect from Java with jTDS
jTDS is an open source JDBC driver for SQL Server and Sybase. Add it to pom.xml:
<dependency> <groupId>net.sourceforge.jtds</groupId> <artifactId>jtds</artifactId> <version>1.3.1</version></dependency>The program below connects to TestDB through the published port 1401, lists the databases on the server and prints the Inventory rows:
public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("net.sourceforge.jtds.jdbc.Driver"); try (Connection conn = DriverManager.getConnection( "jdbc:jtds:sqlserver://localhost:1401/TestDB", "sa", "<YourPassword>"); Statement sta = conn.createStatement()) {
try (ResultSet rs = sta.executeQuery("SELECT Name FROM sys.Databases")) { while (rs.next()) { System.out.println("name: " + rs.getString("Name")); } }
try (ResultSet rs = sta.executeQuery("SELECT * FROM Inventory")) { while (rs.next()) { long id = rs.getLong("id"); String name = rs.getString("name"); int quantity = rs.getInt("quantity"); System.out.println("id: " + id + ", name: " + name + ", quantity: " + quantity); } } }}The container runs a default instance, so the URL gives only host, port and database. Add ;instance=NAME only for a named instance on a Windows server (as in the pool below); jTDS then looks up the instance’s port through the SQL Server Browser service.
Note: jTDS 1.3.1 dates from 2013 and is no longer developed. For new projects use Microsoft’s JDBC driver (com.microsoft.sqlserver:mssql-jdbc) with a URL such as jdbc:sqlserver://localhost:1401;databaseName=TestDB;encrypt=true;trustServerCertificate=true.
Define a JDBC connection pool in GlassFish
In GlassFish (or Payara), a pool and its JNDI resource can be declared in the <resources> section of domain.xml. Copy the jTDS JAR into the domain’s lib directory first. This pool uses jTDS’s XA data source and connects to the named instance LOGO:
<jdbc-resource enabled="true" jndi-name="jdbc/b2bc_mssql" object-type="user" pool-name="b2bc_mssql"></jdbc-resource><jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="table" datasource-classname="net.sourceforge.jtds.jdbcx.JtdsDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="b2bc_mssql" non-transactional-connections="false" ping="false" pool-resize-quantity="2" pooling="true" res-type="javax.sql.XADataSource" statement-cache-size="0" statement-leak-reclaim="false" statement-leak-timeout-in-seconds="0" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="true"> <property name="URL" value="jdbc:jtds:sqlserver://127.0.0.1/b2bc"/> <property name="User" value="b2bc"/> <property name="Password" value="b2bc"/> <property name="serverName" value="127.0.0.1"/> <property name="instance" value="LOGO"/></jdbc-connection-pool>Applications look the data source up as jdbc/b2bc_mssql. The pool keeps 8 connections open (steady-pool-size), grows to at most 32 and closes connections idle for more than 300 seconds.