Reputation: 1
I've read various posts but have not been able to get my java connection to SQL Server 2014 Express to work:
It seems like the code is not able to find the driver.
I placed the file mssql-jdbc-6.2.1.jre8.jar
in the applications build folders.
I tried various options about adding the CLASSPATH, without success, but it seems that this is not necessary for the recent versions of the driver.
I'm NOT using an IDE
//=====================================================================
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
System.out.println("----------------------------------Start Connection---" + "\r\n");
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver:LocalHost:1433;" +
"databaseName=stocksandshares;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
Upvotes: 0
Views: 818
Reputation: 1755
Your connection string is incorrect.
You missed the two forward slashes at the beginning.
Your connection string should be as follows:
jdbc:sqlserver://LocalHost:1433;databaseName=stocksandshares;integratedSecurity=true;
See this Microsoft documentation page that explain how to build the SQL Server connection string.
And do yourself a favour and start useing an IDE.
Upvotes: 1