Sie sind auf Seite 1von 11

JAVA – MS SQL Connection

Requirements
1. SQL Server
2. JAVA SDK
3. Microsoft SQL Server JDBC Driver

Procedure

1. SQL Server Installation


2. SQL Server Configuration
3. SQL Management Studio
4. SQL JDBC Installation
5. SQL JDBC Configuration
6. Loading JDBC Driver & Connecting to Database

1. SQL Server Installation

Install SQL Server like you install any other application. Take care
you tick to install all the components in the window shown below.
2. SQL Server Configuration

There is a bit of configuration needed for the server to allow you to


connect to it from a program.

Open SQL Server Surface Area Configuration


This can be found in Start->Microsoft SQL Server->Configuration
Tools-> SQL Server Surface Area Configuration

Click on Surface Area Configuration for Services and


Connections
Under Remote Connections select Local and Remote connection

Now you will need to restart the SQL Server

You can do it in SQL Server Configuration Manager

This can be found in Start->Microsoft SQL Server->Configuration Tools->


SQL Server Configuration Manager

Right click on SQL Server (MSSQLSERVER) and click Restart

3. SQL Management Studio

Server name will be name of your computer


Select Windows Authentication
Now right click on Databases and create a database so that you can
check the connection latter. In the image above, under Databases
you can see a database ‘nikesh’ that I have created.

You may close SQL Management Studio now

4. SQL JDBC Installation

Now you will need a Java Database Connection Driver for MS SQL

You can download it from


http://www.microsoft.com/downloads/en/confirmation.aspx?familyI
d=99b21b65-e98f-4a61-b811-19912601fdc9&displayLang=en

When you run the downloaded file sqljdbc_2.0.1803.100_enu.exe it


will ask to extract the contents.

Extract it in to your C:\Program Files

It can be extracted to any location. But I recommend you do in


C:\Program Files assuming C:\ is where you have installed
windows.
That’s how my directory looks after extracting the contents.

5. SQL JDBC Configuration

By configuration I mean setting CLASSPATH of JDBC driver for


windows just like you probably did for Java while installing it.

Go to Control Panel -> System Properties -> Advanced


In windows xp you can get here by right clicking My Computer.

Now click on Environment Variables…

And you will find a window like shown below


Click on CLASSPATH and click Edit…

There will be some string in Variable value text field. Do not delete it. Put
a semicolon after the string and copy paste the path of JDBC Driver you
extracted earlier.

In my case it is

C:\Program Files\Microsoft SQL Server JDBC Driver


2.0\sqljdbc_2.0\enu\sqljdbc4.jar

You can copy paste the location from the address bar of the folder and
add ‘\sqljdbc4.jar’

Click ‘ok’

Now you have set CLASSPATH for windows to find the JDBC Driver

Now comes the coding part

6. Loading the JDBC Driver & Connecting to Database

import java.io.*;
import java.lang.*;
import java.sql.*;

public class test1


{
public static void main(String args[])
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e)
{
System.out.println("connection failed"+e);
}

String connectionUrl = "jdbc:sqlserver://localhost:1433;" +


"databaseName=nikesh;integratedSecurity=true;";
try
{
Connection con = DriverManager.getConnection(connectionUrl);

}
catch (Exception e)
{
System.out.println("connection failed"+e);
}
}
}

The code highlighted in red color shows loading the Driver and code
highlighted in blue color shows connecting the database.

Before running the code copy a file called sqljdbc_auth.dll from


C:\Program Files\Microsoft SQL Server JDBC Driver
2.0\sqljdbc_2.0\enu\auth\x64 and paste it in the folder where you have
saved the java program.

String connectionUrl = "jdbc:sqlserver://localhost:1433;" +


"databaseName=nikesh;integratedSecurity=true;";

• Localhost signifies that SQL Server is running in the local


computer. This will be replaced by IP address or name or remote
computer if the SQL Server is running in Remote computer
• 1433 signifies the port number of port through which communication to
the server takes place
• databaseName should be given to know which database you are
accessing.
• IntegratedSecurity=true is ther because we are using Windows
Authentication to access SQL Server.

The code given below will display some information about the database so
you know that the connection is established for sure

import java.io.*;
import java.lang.*;
import java.sql.*;
public class test
{
public static void main(String args[])
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e)
{
System.out.println("connection failed"+e);
}

String connectionUrl = "jdbc:sqlserver://localhost:1433;" +


"databaseName=nikesh;integratedSecurity=true;";
try
{
Connection con = DriverManager.getConnection(connectionUrl);
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+
dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+
dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next())
{
System.out.println("\tcatalog: "+ rs.getString(1));
}

}
catch (Exception e)
{
System.out.println("connection failed"+e);
}
}
}
The code below demonstrates executing of an sql query from Java code

import java.io.*;
import java.lang.*;
import java.sql.*;

public class test3


{
public static void main(String args[])
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch (Exception e)
{
System.out.println("connection failed"+e);
}

String connectionUrl = "jdbc:sqlserver://localhost:1433;" +


"databaseName=nikesh;integratedSecurity=true;";
try
{
Connection con = DriverManager.getConnection(connectionUrl);

java.sql.ResultSet rs = null;
dm = con.getMetaData();
try {
String SQL = "SELECT * FROM emp";
Statement stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("Id") + ", " + rs.getString("Name"));
}

rs.close();
stmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e)
{
System.out.println("connection failed"+e);
}

Das könnte Ihnen auch gefallen