Connecting to sqlserver using kotlin and gradle

Hi

I had difficulty connecting to MS SQL Server in kotlin using gradle earlier today. I do not know if it is appropriate to post this here but I worked out a solution and thought that it might be helpful to others.

As a starting point, because of earlier issues, I had removed all instances of Java greater than version 8 from my computer.

First, relevant sections of build.gradle

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.2.1.jre8'
}

For the actual (kotlin) code (imports first)

import com.microsoft.sqlserver.jdbc.SQLServerDriver;
import java.sql.*
import java.io.File

For setting up the connection:

DriverManager.registerDriver(com.microsoft.sqlserver.jdbc.SQLServerDriver())
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
val dbURL = "jdbc:sqlserver://sssssss\\ssss;user=uuuuuuuuu;password=pppppp"
val connection: Connection = DriverManager.getConnection(dbURL)

where:

  • sssssss\ssss is the identifier for the server provided to be my our IT department
  • uuuuuu is my userid
  • pppppp is my password (which I should not have included directly in the code)
1 Like