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);
}
}
}

Advertisements

About rajkirpal

i am a software engineer. and i have decent knowledge about java technologies like ANDROID, Servlet, Jsp, Struts, Hibernet, Spring, J2ME, Java Script, Ajax, JQuery, CSS. Further i am Preparing Easy understandable materials/documents upon the same java technologies and developing project in core java , advanced java and j2me , ANDROID as per the requirements Also designing the web sites and logos Thank You.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s