JAVA SQL Connection
JAVA SQL Connection
JAVA SQL Connection
Requirements
1. SQL Server
2. JAVA SDK
3. Microsoft SQL Server JDBC Driver
Procedure
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
Now you will need a Java Database Connection Driver for MS SQL
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
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
import java.io.*;
import java.lang.*;
import java.sql.*;
}
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.
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);
}
}
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.*;
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);
}