The Way Of Life: How to Connect Java to SQL Server
Google

Tuesday, June 28, 2011

How to Connect Java to SQL Server


This time, we learn how to connecting Our Java program to Microsoft SQL Server, i hope this article will help you and everyone to code on Java, have fun!

Tools :

1. NetBeans IDE 7.0 download here.
2. SQL Server 2008 Enterprise / SQL Server Express, you can download here.
3. Microsoft JDBC Driver for SQL Server, you can download here. And dont forget to add the library on our Java project.

First, we must create project Java on NetBeans IDE, for the example ConnectSQLServer.
And then create packages by right click on Source Packages and choose New -> Java Packages and create name on that packages for the example same with the Project Name Connect SQLServer.

After that, create one class by right click on our new packages , and choose New -> Java Class and create our New Java Class with SQLServerConnection.java and type or copy paste this code on our new Java Class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

class SQLServerConnection{
Connection Connect;
public Connection ConnectDB(){
String url = "jdbc:sqlserver://localhost:1433;databaseName=tempdb;";
try{

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connect = DriverManager.getConnection(url, "sa", "p455w0rd");

}catch(ClassNotFoundException e){
System.out.println("Driver Load Failed!");
}catch(SQLException e){
System.out.println("Connection Failed!");
}
return Connect;
}


public static void main(String[] abc){
Connection Con = new SQLServerConnection().ConnectDB();
if(Con != null){
System.out.println("Connection Succesfull!");
}else{
System.out.println("Connection Failed!");
}
}
}

If you have finished, then we must create New Java Form by right click on ConnectSQLServer packages and then choose New -> JFrame Form. And create one button and name on it with "Test Connection SQL Server". Let code the button with this code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = new SQLServerConnection().ConnectDB();
try{
if(con != null){
JOptionPane.showMessageDialog(null, "Connection Succesfull!");
}else{
JOptionPane.showMessageDialog(null, "Connection Failed!");
}
}catch(Exception e){

}
}


And Now we can check the code and run the program on NetBeans by press F6, test it!


Labels: , , ,

0 Comments:

Post a Comment

<< Home