Write a java program that connects to a database using JDBC and does add, delete, modify and retrieve operations.

Program Code:
import java.sql.*;
public class JdbcExample
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/jdbc";
static final String USER="root";
static final String PASS="Gcet@05";
public static void main(String args[])
{
Connection conn=null;
Statement stmt=null;
try
{
System.out.println("connecting to database--");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("creating statement--");
stmt=conn.createStatement();
String sql,sql1,sql2,sql3;
Sql1=”insert into employee values(23,’bob’,’s’,20)”;
int s1= stmt.executeUpdate(sql1);
sql2=”update employee set age=18 where id=3”;
int s2= stmt.executeUpdate(sql2);
sql3=”delete from employee where id=24”;
int s3= stmt.executeUpdate(sql3);
sql="SELECT id,first,last,age FROM employee";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int id=rs.getInt("id");
int age=rs.getInt("age");
String first=rs.getString("first");
String last=rs.getString("last");
System.out.println("ID:"+id);
System.out.println("Age:"+age);
System.out.println("First:"+first);
System.out.println("Last:"+last);
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
System.out.println("Goodbye");
}
}

MYSQL:
MYSQL>create database jdbc;
MYSQL> use jdbc;
MYSQL>create table employee(id int,first varchar(20),last varchar(20),age int);
MYSQL>insert into employee values(2,’siri’,’m’,23);
MYSQL>select * from employee
Id first last age
2 siri m 23
3 deep v 20
24 sagar k 24

Output:
connecting to database—
creating statement—
id:2 first:siri last:m age:23
id:3 first:deep last:v age:18
id:23 first:bob last:s age:20
Goodbye
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: