I've started supporting Microsoft JDBC Driver for SQL server. The driver provides Java database connectivity from any Java application, application server, or Java-enabled applet. As a beginner of Java programming, I am writing this tutorial to record how to create a simple console Java application to connect SQL server using JDBC Driver.
Download and install JDK from https://www.oracle.com/technetwork/java/javase/downloads/index.html, in this tutorial we will use JDK 8 (8u181) as it is the recommended Java Version for JDBC Driver 7.0.
As we will use
javac.exeto compile the Java program, we need to addC:\Program Files\Java\jdk1.8.0_181\binto thePathvariable so we can calljavac.exefrom anywhere.
Download Microsoft JDBC Driver 7.0 for SQL Server from: https://www.microsoft.com/en-us/download/details.aspx?id=57175.
Run
sqljdbc_7.0.0.0_enu.exeand unzip the content to anywhere you like, we will extract it toC:\jdbc7in this tutorial.You will find the JDBC package for JRE8 at:
C:\jdbc7\sqljdbc_7.0\enu\mssql-jdbc-7.0.0.jre8.jar, let’s set it as classpath in System variables so that the compiler is able to find it.
Create a folder for the JDBC test application:
C:\jdbc-app.Save following application code to C:\jdbc-app\JDBCTest.java
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCTest { public static void main(String[] args) { String connectionUrl = "jdbc:sqlserver://192.168.199.221:1433;databaseName=TestDB;integratedSecurity=true"; try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();) { String SQL = "SELECT TOP 10 * FROM Person;"; ResultSet rs = stmt.executeQuery(SQL); while (rs.next()) { System.out.println(rs.getString("Name")); } } catch (SQLException e) { e.printStackTrace(); } } }In this tutorial, we use integrated authentication to authenticate a remote SQL server. We will need the
sqljdbc_auth.dllfor integrated authentication to work. You can findsqljdbc_auth.dllatC:\jdbc7\sqljdbc_7.0\enu\auth\x64(orC:\jdbc7\sqljdbc_7.0\enu\auth\x86for a 32bit OS). Let's copysqljdbc_auth.dlltoC:\jdbc-app.Add
C:\jdbc-appto classpath as well.
Run a command prompt, cd to
C:\jdbc-app, runjavac JDBCTest.javato compile the test application, it will createJDBCTest.classwhen it completes.Run
java JDBCTestto test the console application.C:\jdbc-app>javac JDBCTest.java C:\jdbc-app>java JDBCTest John Marry Kevin C:\jdbc-app>