Microsoft JDBC Driver for SQL Server
Difference between sqljdbc.jar and sqljdbc4.jar -
To support backward compatibility and possible upgrade scenarios, the JDBC Driver includes 2 JAR class libraries in each installation package: sqljdbc.jar and sqljdbc4.jar.
sqljdbc.jar class library provides support for JDBC 3.0.
sqljdbc.jar class library requires a Java Runtime Environment (JRE) of version 5.0. Using sqljdbc.jar on JRE 6.0 will throw an exception when connecting to a database.
sqljdbc4.jar class library provides support for JDBC 4.0. It includes all of the features of the sqljdbc.jar as well as the new JDBC 4.0 methods.
sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0. Using sqljdbc4.jar on JRE 1.4 or 5.0 will throw an exception.
Find more at: System Requirements for the JDBC Driver
Enable TCP/IP connection in SQL Server Configuration Manager -
All Programmes
-> SQL Server Configuration Manager
-> SQL Server Network Configuration
-> TCP/IP (Enable)
-> SQL Server Services
-> SQL Server (Restart)
If you use Windows Authentication -
Set JDBC URL like: jdbc:sqlserver://localhost;integratedSecurity=true;
And copy sqljdbc_auth.dll to JRE library like: D:\Java\JDK1.7.0_21\jre\lib\ext
(Not required if you use SQL Server Authentication)
If you want to change Server Authentication Mode, please see -
Change Server Authentication Mode
Two ways to create connection -
1. Class.forName + connectionUrl
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://localhost:1433;"
+ "databaseName=AdventureWorksDW2008R2;user=sa;password=sa";
conn = DriverManager.getConnection(connectionUrl);
2. SQL Server Data Souce
import com.microsoft.sqlserver.jdbc.*;
SQLServerDataSource ds = new SQLServerDataSource();
ds.setUser("sa");
ds.setPassword("sa");
ds.setServerName("localhost");
ds.setPortNumber(1433);
ds.setDatabaseName("AdventureWorksDW2008R2");
conn = ds.getConnection();
Three types of statement -
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from world.city");
pstmt = conn.prepareStatement("SELECT id, name, countrycode, district, population from world.city");
rs = pstmt.executeQuery();
pstmt = conn.prepareStatement("delete from world.city where name = ? ; ");
pstmt.setString(1, "AAA");
pstmt.executeUpdate();
cstmt = conn.prepareCall("{call dbo.uspGetEmployeeManagers(?)}");
cstmt.setInt(1, 50);
rs = cstmt.executeQuery();
No comments:
Post a Comment