Wednesday 1 October 2014

First JDBC Application

Step 1 : import sql package
             import java.sql.*;

Step 2: Register jdbc driver. By using below statement, we are loading main driver class into the JVM.
       Ex : Class.forName("com.mysql.jdbc.Driver");

Step 3: Open connection to database, using DriverManager class.
      Ex:
      String url = "jdbc:mysql://localhost/sample";
      String userName = "root";
      String pasword = "tiger";
      Connection con = DriverManager.getConnection(url, userName, pasword);

      jdbc:mysql://localhost/sample
      Above string is a database connection string.

      jdbc:mysql:// = java database connection to a mysql database
      localhost = mysql database is on local machine
      sample = name of database being connected to

Step 4: Execute queries
/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    public static void main(String args[]) throws SQLException, ClassNotFoundException{
        /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/sample";
        String userName = "root";
        String pasword = "tiger";
        Connection conn = DriverManager.getConnection(url, userName, pasword);
        
        /* Create table employee */
        String query = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
        Statement stmt = conn.createStatement();
        stmt.execute(query);     
        
        /* Insert data to employee table */
        query = "INSERT INTO employee values(1, \"Krishna\")";
        stmt.execute(query);
        query = "INSERT INTO employee values(2, \"Arjun\")";
        stmt.execute(query);
        
        query = "SELECT * FROM employee";
        ResultSet rs = stmt.executeQuery(query);
        
        while(rs.next()){
            int id  = rs.getInt("id");
            String name = rs.getString("name");
            System.out.println(id +" " + name);
        }
 rs.close();
        conn.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
1 Krishna
2 Arjun

String url = "jdbc:mysql://localhost/sample";

In the above string,'sample' is the database name. You can create database using below sql command.

CREATE DATABASE sample;






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment