Reputation: 1
How can I connect to Microsoft SQL Server from my java code?
Code:
public class insert {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
String url = "jdbc:microsoft:sqlserver://LENOVO-PC\\SQLEXPRESS;DatabaseName=dbtest";
Connection connection = DriverManager.getConnection(url , "sa" , "Aa123456");
Statement st = connection.createStatement();
st.executeUpdate("INSERT INTO [dbo].[table] VALUES ('come')");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
Error:
java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at insert.main(insert.java:12)
Microsoft SQL Server name is: LENOVO-PC\SQLEXPRESS and sqljdbc.jar is already added to the referenced libraries.
Upvotes: 0
Views: 73
Reputation: 108939
The class name com.microsoft.jdbc.sqlserver.SQLServerDriver
you're trying to load is from a very old version of the Microsoft SQL Server 2000 version of the driver. Around 2005, Microsoft changed this to com.microsoft.sqlserver.jdbc.SQLServerDriver
(notice the switch in order between jdbc
and sqlserver
). At that time, they also changed the driver URL prefix from jdbc:microsoft:sqlserver:
to jdbc:sqlserver:
.
In other words, you need to:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver")
(optional, driver will be loaded automatically)jdbc:sqlserver://LENOVO-PC\\SQLEXPRESS;databaseName=dbtest
(note the prefix change and DatabaseName
-> databaseName
. See also Building the Connection URL.With recent JDBC drivers, it is not necessary to explicitly load the driver class in simple Java applications, so instead of step 1, you could also remove the Class.forName
line.
Also make sure you are using a recent version of the driver, see the mssql-jdbc project on GitHub (latest stable version at time of writing is 7.0.0).
Upvotes: 1
Reputation: 3677
Correct the driver class name:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Upvotes: 0