Sie sind auf Seite 1von 3

EXPERIMENT-6

ABHISHEK CHOUDHARY
07311503113
AIM
Write a program of database connectivity using JDBC
(A) To display details of all employees
(B) To display details of an employee by taking employee id by user
(A) SOURCE CODE
import java.sql.*;
public class jdbc1
{
static final String
static final String
static final String
static final String

JDBC_DRIVER="com.mysql.jdbc.Driver";
DB_URL="jdbc:mysql://localhost/";
user="root";
pass="";

public static void main(String arg[])


{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL+"company",user,pass);
stmt=conn.createStatement();
String sql;
sql="select * from employee";
ResultSet rs=stmt.executeQuery(sql);
System.out.println("-------------------------");
System.out.print("ID"+"\t");
System.out.print("NAME"+"\t");
System.out.println("SALARY");
System.out.println("-------------------------");
while(rs.next())
{
int id=rs.getInt("id");
String name=rs.getString("name");
int salary=rs.getInt("salary");
System.out.print(id);
System.out.print("\t"+name);
System.out.println("\t"+salary);
}
rs.close();
stmt.close();
conn.close();
}

catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT

(B) SOURCE CODE


import java.util.Scanner;
import java.sql.*;
public class jdbc2
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/";
static final String user="root";
static final String pass="";
static Scanner sc=new Scanner(System.in);
public static void main(String arg[])
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL+"company",user,pass);
int sid;
System.out.print("Enter Employee ID to search : ");
sid=sc.nextInt();

stmt=conn.createStatement();
String sql;
sql="select * from employee where id="+sid;
ResultSet rs=stmt.executeQuery(sql);
System.out.println("-------------------------");
System.out.print("ID"+"\t");
System.out.print("NAME"+"\t");
System.out.println("SALARY");
System.out.println("-------------------------");
while(rs.next())
{
int id=rs.getInt("id");
String name=rs.getString("name");
int salary=rs.getInt("salary");
System.out.print(id);
System.out.print("\t"+name);
System.out.println("\t"+salary);
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT

Das könnte Ihnen auch gefallen