Java, JDBC and SQL Server tutorial

PostgreSQL and MySQL have always been the go-to databases for Java development. However, as more developers move into the Microsoft Azure cloud, or get enticed by features Microsoft has weaved into its GitHub platform, developers increasingly find themselves adopting Microsoft technologies. Thus, the integration of Java, JDBC and SQL Server is increasingly common.

Java, SQL Server and JDBC tutorial

In this Microsoft SQL Server and JDBC tutorial, you'll learn how to connect to a Microsoft SQL Server in Java using JDBC. The steps are relatively straightforward:

  1. Install SQL Server and ensure the systems administrator (SA) account is enabled.
  2. Create a new database in SQL Server.
  3. Build a Java program with Maven or Gradle that includes the SQL Server driver dependency.
  4. Configure a properly formatted SQL Server JDBC URL.
  5. Use the JDBC driver and URL to establish a database connection.
  6. Use the JDBC connection to speak to the database through SQL.
  7. Close all active database connections when you're done.

Tips for connecting to SQL Server in Java

Each database is different, so connecting to Postgres is a little different from connecting to MySQL, which is different from connecting to SQLite. Watch out for the following pitfalls when doing JDBC with SQL Server for the first time:

  1. Make sure SQL Server security is set to SQL Server and Windows Authentication mode.
  2. Ensure the SA account, or whatever account you connect with, is active and enabled. \
  3. Add encrypt=false to the JDBC URL for SQL Server.
  4. Make sure the server is running and listening on port 1433.
  5. Make sure the SQL Server JDBC drivers physically exist in your Java project.

With these five issues taken care of, a developer will be able to connect to their Java programs to SQL Server without issue.

Screenshot of a SQL Server JDBC URL.
An incorrect JDBC URL is the most common mistake when developers connect to MySQL from Java.

Microsoft's flagship database, and Java's versatility as a language, makes them a strong pair. With JDBC bringing the two together, it's easy to develop high-performing, enterprise-grade applications that are both scalable and secure.

Cameron McKenzie has been a Java EE software engineer for 20 years. His current specialties include Agile development; DevOps; Spring; and container-based technologies such as Docker, Swarm and Kubernetes.

View All Videos