Wednesday, February 7, 2007

Java: Connect to DB using JDBC Drivers

1 comment:

Contact: highbrow.admin@gmail.com said...

/**
This is the class to connect to the Mssql DB using jtds driver. Here I am assuming there is a DB called hotwave with user name "hotwave" and password "password" already exist. Problem faced while executing this is "Class Not Found: net.sourceforge.jtds.jdbc.Driver". so I copied jtds1.0 jar to my current folder and extracted to the same folder. Now it is working fine.
*/
import java.sql.*;
public class DBConnect{
public static void main(String args[]){

String dbServer = "MSSQL";
String dbServerUser = "hotwave";
String dbServerPasswd = "password";
String dbServerHost = "localhost";
String dbServerPort = "1433";

try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String dbServerUrl = "jdbc:jtds:sqlserver://" + dbServerHost + ":" + dbServerPort+ "/hotwave";

System.out.println("Connecting to " + dbServerUrl + "with " + dbServerUser + ":" + dbServerPasswd);
Connection conn = DriverManager.getConnection( dbServerUrl , dbServerUser,dbServerPasswd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from HW_USER");

while(rs.next()){
String userName = rs.getString("name");
System.out.println("UserName is :"+userName);
}

}catch(Exception ee) {
ee.printStackTrace();
}

}
}
OUTPUT: D:\MyJavaFiles>java DBConnect
Connecting to jdbc:jtds:sqlserver://localhost:1433/hotwave with hotwave:password
UserName is :Mac
UserName is :system
UserName is :Sam
UserName is :Bill
UserName is :Bob
UserName is :Moy
UserName is :Nil
UserName is :Sarp
UserName is :Lawst
D:\MyJavaFiles>