Wednesday, January 2, 2013


How to connect to SQL Database-JDBC connection

1. How to connect to SQL Database

Steps to connect SQL Database (using JDBC Driver)
1. Import the SQL package.
2. Create an Connection Object and initialize to NULL.
3. Create an String variable for URL and store the URL.
4. Create an String variable for DATABASE and store Database Name.
5. Create an String variable for DRIVER and store the JDBC driver.
6. Create an String variable for USERNAME and store UserName.
7. Create an String variable for PASSWORD and store Password.
8. Put an try catch Block, inside try add the following logic.
    1. Create an instance of DRIVER
    2. Pass the URL, DATABASE, USERNAME, PASSWORD to getConnection()
       method of DriverManager, and pass it to Connection Object.
   3. Create an STATEMENT Object which acts as a reference  to Create SQL   
       Statement for the Connection.
   4. Through the STATEMENT Object Execute any Query, and pass it to Object
       of RESULT SET.
   5. Loop through RESULT SET Object and can print the data.
   6. Close the Connection through Connection object.

-----------------------------------------------------------------------------------------------------------------------------
import java.sql.*
public class Connect_DB{

public static void main(String[] args){
      
     Connection conn = NULL;
     String url= "jdbc:mysql://localhost:3306";
     String dbName = "MidMac";
     String driver = "com.mysql.jdbc.Driver";
     String username = "root";
     String password = "tiger";
     
     try{
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbNameusername, password);
            Statement Smt = conn.createStatement();
            ResultSet Rs = Smt.executeQuery("SELECT * FROM EMPLOYEE");
            
            while(Rs .next()){
              System.out.println(Rs.getString(1));
            }//end while
      }catch(Exception e){
            conn.close();
      }
     
}

}

-----------------------------------------------------------------------------------------------------------------------------

1 comment:

  1. Very nice post really very helpful Vishva

    ReplyDelete

Total Pageviews