Today I will show you how to connect with database server using Java.
Here, I have used PostGre Sql as my database server and I have uploaded the PGSQL.Jar (the postgre sql driver) for your convenience.
** I have used the OldVersion of NetBeans (NetBeans IDE 5.0) and JDK 1.4.2.
** Another matter, You have to include the pgsql.jar in your classpath while compiling and running this project.
** Download pgsql.jar from http://www.ziddu.com/download/12613415/pgsql.jar.html
package dbconnection;
import java.sql.*;
public class dbConnection extends javax.swing.JFrame {
private void myInit()
{
/************************DB Connection Started********************/
Connection result = null;
String DB_CONN_STRING =”jdbc:postgresql://localhost:5432/replicationdb”;
String DRIVER_CLASS_NAME = “org.postgresql.Driver”;
String USER_NAME = “XYZ”;
String PASSWORD = “pass”;
try {
Class.forName(“org.postgresql.Driver”);
}
catch (ClassNotFoundException cnfe){
System.out.println(“Couldn’t find the driver!”);
System.out.println(“Let’s print a stack trace, and exit.”);
cnfe.printStackTrace();
System.exit(1);
}
try {
result = DriverManager.getConnection(“jdbc:postgresql://localhost:5432/Test”, USER_NAME, PASSWORD);
}
catch (SQLException se){
System.out.println(“Couldn’t connect: print out a stack trace and exit.”);
se.printStackTrace();
System.exit(1);
}
/*******************DB Connection finished***************************/
}
public dbConnection() {
initComponents();
myInit();
}
/***************Auto Generated Code by NetBeans—-Started from here *****************
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
setForeground(java.awt.Color.white);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 446, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 350, Short.MAX_VALUE)
);
pack();
}
/******************** Auto Generated Code by NetBeans—-Ended*******************/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new dbConnection().setVisible(true);
}
});
}
}