To create JDBC Connection with MS SQL Server we need following things.
- Microsoft SQL Server JDBC Driver( Download from here)
- SQL JDBC Authentication file (Download from here)
Note: SQL JDBC Authentication file is platform dependent (X86 or X64) so download accordingly.
After download the authentication file copy this file to window’s system32 folder.
now set the class path for SQL Server JDBC driver(jar file ).
now suppose you have a database mssumit , user name and password is sumit.
you can also connect to SQL Server with widows authentication .
you can use the following code if you want to connect with windows authentication
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=mssumit;integratedSecurity=true");If you want to connect with user name password then use the following code.
Connection conn =DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=mssumit;user=sumit;password=sumit;");Sometime it is possible that you are unable to connect with user name in that case please check database connection properties that you are able to connect with SQL Server Authentication.
instantiate the SQL Server driver class with the following code.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();Now create a Connection with help of DriverManager. we are using MS Sql Server Authentication to get the connection.
Connection conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=mssumit;user=sumit;password=sumit;");Now get a Statement object from connection object with the help of the following code.
Statement statement=conn.createStatement();
Now suppose we have a user table and want to get all the attribute.we get the ResultSet object as follows.
ResultSet resultSet=statement.executeQuery("select * from [user]");Now to view the records of the table use the following code.
while(resultSet.next()){
System.out.println(" "+resultSet.getString(1)+" "+resultSet.getNString(2));
}