https://docs.microsoft.com/en-us/sql/connect/jdbc/working-with-a-connection?view=sql-server-ver15
Use Class.forName
to prevent No suitable driver found for jdbc:sqlite error:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Create connection url with required variables
String connectionUrl = "jdbc:sqlserver://localhost;database=AdventureWorks;integratedSecurity=true;"
eg,
String connectionUrl = "jdbc:sqlserver://192.168.XX.XXX;DatabaseName=dbName;user=" + user + ";password=" + pass;
Connect and return the connection
Connection con = DriverManager.getConnection(connectionUrl);
Instead of using the latest version, use older version of mssql-jdbc Maven dependency
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.2.2.jre11</version>
</dependency>
Connection conn = null;
String user = "user";
String pass = "password";
String connectionUrl = "jdbc:sqlserver://192.168.XX.XXX;DatabaseName=dbName;user=" + user + ";password=" + pass;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(connectionUrl);
Statement stmt = null;
String query = "select * from Videos";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString("VideoID");
System.out.println(name);
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
sql
database
java
maven
driverManager