JDBC
JDBC
JDBC
-->
import java.sql.*;
import java.io.*;
public class StudentTable
{
public static void main(String args[])
{
try
{
String sql;
ResultSet results;
//a) Connection To A Database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
String URL = "jdbc:odbc:Student";
Connection con = DriverManager.getConnection(URL);
System.out.println("Connection to database created.");
Statement state = con.createStatement();
System.out.println("Statement Object Created.");
//b) Insert a Record
sql = "insert into StudTable values(6, 'XYZ')";
state.executeUpdate(sql);
System.out.println("Entry Inserted.");
//c) Change name as John where Roll No. is 2
sql = "update StudTable set StudentName = 'John' where Roll = 2";
state.executeUpdate(sql);
System.out.println("Entry Updated.");
//d) Delete Current Record
sql = "delete * from StudTable where Roll = 4";
state.executeUpdate(sql);
System.out.println("Entry Deleted.");
//e) Display whole contents of Database.
sql = "select Roll, StudentName from StudTable";
results = state.executeQuery(sql);
String text = "" ;
while(results.next())
{
text += results.getInt(1) + "\t" + results.getString(2) + "\n";
}
System.out.println("\nROLL\tNAME");
System.out.println(text);
results.close();
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.sql.*;
public class EmployeeTableUpdate
{
public static void main(String args[])
{
try
{
String sql;
ResultSet results;
PreparedStatement state;
String text;
//a) Establish Connection To Database.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
String URL = "jdbc:odbc:EmployeeDatabase";
Connection con = DriverManager.getConnection(URL);
System.out.println("Connection to database created.");
//b) Insert Record Using PreparedStatement
sql = "insert into Employee values(?, ?)";
state = con.prepareStatement(sql);
state.setString(1, "XYZ");
state.setInt(2, 21);
state.executeUpdate();
System.out.println("\nRecord Inserted.");
//c) Select All Entries Related to "Ramesh"
sql = "select * from Employee where Name = ?";
state = con.prepareStatement(sql);
state.setString(1, "Ramesh");
results = state.executeQuery();
text = "" ;
while(results.next())
{
text += results.getString(1) + "\t" + results.getInt(2) + "\n";
}
System.out.println("\nEntries Related To Ramesh.");
System.out.println("NAME\tAGE");
System.out.println(text);
//d) To delete the record of Database
sql = "delete * from Employee where Name = ?";
state = con.prepareStatement(sql);
state.setString(1, "ABC");
state.executeUpdate();
System.out.println("\nEntry Deleted.");