JDBC Connection Part 1

Posted by Unknown On Saturday 23 February 2013 0 comments

JDBC Connection


Hello friends now we are going to discuss about Java Data Base Connectivity. We heard connecting Java and DB are so difficult, etc. and blab bla bla …… :) We are going to show you much easy it is. Only want to follow some regular steps.

JDBC is application programing interface .that allow programmers to access Data Base Systems from java code .it allows to execute SQL queries on java program.it helps programmers to connect, send receive data from DB.

JDBC uses application programing technology for driver manager and Data Base specific drivers, for providing transparency and concurrency to heterogeneous Data Bases. Creating JDBC programs understanding its architecture make easier.

JDBC have layered Architecture.




When using JDBC we can follow following steps.

1.      Loading JDBC driver.
2.      Establishing connection.
3.      Executing SQL statements.
4.      Getting result.
5.      Closing connection.



There is an interface in  java.sql package that specifies connection with specific database called connection 


 Connection conn = null;
DriverManager:

It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):

This method establishes a connection to specified database url. It takes three string types of arguments like: 

    url: - Database url where stored or created your database
    userName: - User name of MySQL
    password: -Password of MySQL 

con.close():

This method is used for disconnecting the connection. It frees all the resources occupied by the database.



SOURCE CODE.
import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  catch (Exception e) {
  e.printStackTrace();
  }
  }
}

0 comments:

Post a Comment

Fashion