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:
- Install SQL Server and ensure the systems administrator (SA) account is enabled.
- Create a new database in SQL Server.
- Build a Java program with Maven or Gradle that includes the SQL Server driver dependency.
- Configure a properly formatted SQL Server JDBC URL.
- Use the JDBC driver and URL to establish a database connection.
- Use the JDBC connection to speak to the database through SQL.
- 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:
- Make sure SQL Server security is set to SQL Server and Windows Authentication mode.
- Ensure the SA account, or whatever account you connect with, is active and enabled. \
- Add encrypt=false to the JDBC URL for SQL Server.
- Make sure the server is running and listening on port 1433.
- 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.
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.