Monday, July 11, 2011

JAVA and MSSQL database connection steps and Code

/*
JAVA AND MSSQL DATABASE CONNECTIVITY
Help Steps:

JAVA- AND MS-SQL DATABASE CONNECTION STEPS [rk]

Step 1: Create your instance using the sqlexpre.exe file select the required
settings during the setup.

Step 2.After creating the instance open the sql server conf manager

Step 3.Enable the tcp/ip and do the required settings for the port no (1433) and local host ip address (127.0.0.1)

Step 4. start the created instance.

Step 5. open the cmd prompt

Step 6. c:\>sqlcmd

Step 7. c:\>sp_databasesc:\>go (Note: this command will show u the
default databases)

Step 8. c:\>create database databasename c:\>go

Step 9. c:\>exit

Ster 10.Add the requires version of .jar file means driver into the libraries folder in your project.

Step 11. open the services window in netbeans

Step 12. RClick on the database option select the new connection option.

Step 13. load the appropriate driver in the basic settings tab. (your .jar file of
the driver)

Step 14. give the required values in the shows fields.

*/


import java.sql.*

class JavaMsSqlServer
{
public static void main(String rk[])
{
try
{
//Load and register SQL Server driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

//Establish a connection
Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://serverjag:1433","sa","");

//Create a Statement object
Statement stmt = conn.createStatement();

//Create a ResultSet object, execute the query and return a resultset
ResultSet rset = stmt.executeQuery("SELECT * FROM TABLENAME");


while (rset.next())
{
System.out.println(rs.getString(1));
}

//Close the ResultSet and Statement
rset.close();

stmt.close();

//Close the database connection
conn.close();

}
catch(Exception e)
{
System.out.println("ERROR : "+e);
}
}
}

No comments:

Post a Comment