Java – Connect to SQL Server on Ubuntu No.5

In this blog, how to connect to SQL Server on Ubuntu using Java is shown.

▼1. What is SQL Server on Ubuntu

SQL Server is Relational Database (RDB) provided by Microsoft. SQL Server works on both Windows and Linux. we can use free trial version which is called as “Express Edition” within 180 days.


▼2. How to connect to SQL Server on Ubuntu

2-1. Installing SQL Server on Ubuntu

Quickstart: Install SQL Server and create a database on Ubuntu

2-2. Installing Microsoft JDBC Driver 8.2 for SQL Server

Installing Microsoft JDBC Driver 8.2 for SQL Server (tar.gz) from Release notes for the Microsoft JDBC Driver for SQL Server

Unzip tar –zxvf ./sqljdbc_xxx_enu.tar.gz. under sqljdbc_x.x/enu/ path, mssql-jdbc-x.x.x.jre8.jar or mssql-jdbc-x.x.x.jre11.jar or mssql-jdbc-8.2.0.jre13.jar etc are available according to JDK version

In IntelliJ IDEA, you can add the JDBC Driver for SQL Server from File –> Project Structure –-> Libraries.

2-3. Connection String of JDBC Driver for SQL Server

Referring to Make a simple connection to a database

I use Database TestDB which I created before and use sa user and password as SQL authentication.

import java.sql.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConnectionSQLSrv {
    private static final Logger log = LoggerFactory.getLogger(ConnectionSQLSrv.class);
    public static void main(String[] args){
        Connection con = null;
        try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;user=sa;password=password1234;";
            con = DriverManager.getConnection(connectionUrl);
            log.info("Connect to SQL Server successfully");
        }catch(ClassNotFoundException e){
            log.error("Error Message: ",e);
        }catch(SQLException se){
            log.error("Error Messages: ",se);
        }finally{
            try{
                if (con != null) {
                    con.close();
                    log.info("The connection is closed");
                }
            }catch(SQLException sec){
                log.error("Error MEssages of fin ",sec);
            }
        }
    }
}

2-4. Output of this code

[main] INFO ConnectionSQLSrv - Connect to SQL Server successfully
[main] INFO ConnectionSQLSrv - The connection is closed

▼3. Reference

That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *