Wednesday, January 2, 2013

Simple Program to Connect to MS SQL Server from java Using JDBC

  1. Download the latest JDBC Driver for MS SQL Server from Microsoft JDBC Driver 4.0 for SQL Server. 
  2. Download the zip file and extract it.And find sqljdbc4.jar from it and copy it for later use in classpath or also you can put it in classpath environmental variable.
  3. Write the java program. Before writing java program make sure you have installed appropriate JDK version and correctly set the environment variable.
  4. import java.sql.*;
    class TestMSSql
    {
     public static void main(String args[]) throws Exception
     {
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=JDBCDemo","sa","123");//repalce your databse name and user name
     Statement st=con.createStatement();
     ResultSet rs=st.executeQuery("Select * from login");//replace your table name
     while(rs.next())
     {
      String s1=rs.getString(1);
      String s2=rs.getString(2);
      System.out.println("UserID:"+s1+"Password:"+s2);
     }
    con.close();
    }
    }
  5. Create a databse named "JDBCDemo" using Microsoft SQL Server Managemnt Studio.
    1. Start>All Programs>Microsoft SQL Server 2008> Microsoft SQL Server Managemnt Studio
    2.  Connect to Database Engine using your windows authentication or SQL Server authentication. In this case i am using "sa" as my username and "123" as password for login.
    3. In the Object Explorer right click on Database and click New Database
    4. Give the database name viz.JDBCDemo and choose the owner viz. user of the computer
    5. Create a table viz. login with two fields UserID and Password as nvarchar data type.
    6. Insert data into table to check the program.
  6. Before  running the program make sure TCP/IP Service is enabled as follows
    1. Start>All Programs>Microsoft SQL Server 2008>Configuration tools>SQL Server Configuration Manager
    2. Expand Sql Server Network Configuration choose your MS SQL Server Instance viz. MSQSLSERVER and enable TCP/IP..that's it
  7. Open a command prompt viz. Ctrl+R>cmd hit enter.
  8. Compile the program viz. javac TestMSSql.java
  9. Set the jar classpath viz. set classpath=C:\sqljdbc4.jar;.; 
  10. Run the program viz. java TestMSSql


     

2 comments:

  1. Really thanks Mr.Pradyumna Swain . Your blog is really heedful for me.keep it up..

    ReplyDelete
  2. Very useful blog. Nice job Mr. Pradyumna. Keep it up

    ReplyDelete