java database connectivity

 Steps:

7 Steps to Connect Application to database

1)Import the package

2)Load and Register driver

3)Create Connection

4)Create Statement

5)Execute the query

6)process the results

7)close connection


package jdbc;


import java.sql.*;

import java.sql.Connection;

import java.sql.DriverManager;





//7 Steps to Connect Application to database

//

//1)Import the package

//

//2)Load and Register driver

//

//3)Create Connection

//

//4)Create Statement

//

//5)Execute the query

//

//6)process the results

//

//7)close connection


PROGRAM:

package jdbc;

import java.sql.*;

import java.sql.Connection;

import java.sql.DriverManager;


public class Democlass {

// program to fetch data from mysql

public static void main(String[] args) throws Exception {

String url ="jdbc:mysql://localhost:3306/telusko"; //telusko: name of db

String uname = "root";

String pass = "root";

String query = "select * from master";

Class.forName("com.mysql.cj.jdbc.Driver");// forname for telusko

Connection con = DriverManager.getConnection(url,uname,pass);

Statement st = con.createStatement();

ResultSet rs = st.executeQuery(query);

while(rs.next()) { //rs.next helps to shift pointer to next section!

String userdata = rs.getInt(1) + " : " + rs.getString("userName");

System.out.println(userdata);

}

st.close();

con.close();

}


}

Output:  mahesh


My sql query:

use telusko;

create table master(

userId int,

    userName varchar(30)

);


insert into master (userId,userName) values (1,"Rani");

insert into master (userId,userName) values (2,"Navin");

insert into master (userId,userName) values (3,"Mahesh");


select * from master

o/p: 

userId     UserName

1        Rani
2        Navin
3        Mahesh






Comments