Java Programming
Java Programming
Java Programming
Java Programming
Digital Assignment – 3
17BIT0294
Chandra Teja. P
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
// Establishing Connection
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
if (con != null)
System.out.println("Connected");
else
System.out.println("Not Connected");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Connected
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully Registered
// Updating database
String q1 = "UPDATE userid set pwd = '" + newPwd +
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Password Successfully Updated");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Password Successfully Updated
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
One User Successfully Deleted
// SELECT query
String q1 = "select * from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
{
System.out.println("User-Id : " + rs.getString(1));
System.out.println("Full Name :" + rs.getString(3));
System.out.println("E-mail :" + rs.getString(4));
}
else
{
System.out.println("No such user id is already registered");
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output :
User-Id : id1
Full Name : Teja
E-mail : [email protected]