- Download the latest JDBC Driver for MS SQL Server from Microsoft JDBC Driver 4.0 for SQL Server.
- 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.
- Write the java program. Before writing java program make sure you have installed appropriate JDK version and correctly set the environment variable.
-
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 nameStatement st=con.createStatement();ResultSet rs=st.executeQuery("Select * from login");//replace your table namewhile(rs.next()){String s1=rs.getString(1);String s2=rs.getString(2);System.out.println("UserID:"+s1+"Password:"+s2);}con.close();}}
- Create a databse named "JDBCDemo" using Microsoft SQL Server Managemnt Studio.
- Start>All Programs>Microsoft SQL Server 2008> Microsoft SQL Server Managemnt Studio
- 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.
- In the Object Explorer right click on Database and click New Database
- Give the database name viz.JDBCDemo and choose the owner viz. user of the computer
- Create a table viz. login with two fields UserID and Password as nvarchar data type.
- Insert data into table to check the program.
- Before running the program make sure TCP/IP Service is enabled as follows
- Start>All Programs>Microsoft SQL Server 2008>Configuration tools>SQL Server Configuration Manager
- Expand Sql Server Network Configuration choose your MS SQL Server Instance viz. MSQSLSERVER and enable TCP/IP..that's it
- Open a command prompt viz. Ctrl+R>cmd hit enter.
- Compile the program viz. javac TestMSSql.java
- Set the jar classpath viz. set classpath=C:\sqljdbc4.jar;.;
- Run the program viz. java TestMSSql
Wednesday, January 2, 2013
Simple Program to Connect to MS SQL Server from java Using JDBC
Subscribe to:
Posts (Atom)