Sunday, November 22, 2009

How to connect Sql Server 2005 in Java

import java.sql.*;
///////////////////////////////////////////////////////////////////////////
//1) download sel server 2005 driver from :
//http://msdn.microsoft.com/en-us/data/aa937724.aspx
//OR
//http://www.microsoft.com/downloads/details.aspx?FamilyID=99b21b65-e98f-4a61-b811-19912601fdc9&displaylang=en
//2) set sqljdbc4.jar in your class path.
//3) and run the code.
// By: Amit

//////////////////////////////////////////////////////////////////////////

public class SqlSvrConn
{
public static void main(String[] srg)
{
String driverName= "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//String dbURL = "jdbc:sqlserver://PUT-SQLSERVER-IP-HERE:1433;DatabaseName=PUTDATABASENAMEHERE";
String dbURL = "jdbc:sqlserver://230.100.100.100:1433;DatabaseName=TestDB";
String userName="myusername";
String userPwd="mypassword";
Connection dbConn;
try
{
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL,userName,userPwd);
System.out.println("Connection Successful!");
Statement sta = dbConn.createStatement();
ResultSet res = sta.executeQuery("SELECT TOP 10 * FROM emp");
System.out.println("Customers");
while (res.next()) {
String firstName = res.getString("nName");
String emailName = res.getString("Emailid");
System.out.println(" "+firstName+" "+emailName);
}
dbConn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

No comments:

Post a Comment