Module 5.pptx
Module 5.pptx
Figure reference
Advanced Java Programming
by Mr. Kute T. B.
Class.forName("com.mysql.jdbc.Driver");
Statement
stmt=con.createStatement();
ResultSet rs =
stmt.executeQuery("select * from
Employees");
while(rs.next()) {
System.out.println(
rs.getInt(1)+" "+
rs.getString(2) )+" "+
rs.getString(3)+" "+
rs.getString(4));
}
String name;
int age;
do
{
name = rs.getString(“name”);
age = rs.getInt(“age”);
System.out.println(name+“--”+age);
} while(rs.next());
con.close();
try
{
Class.forName("com.mysql.jdbc.Driver");
} catch(ClassNotFoundException e) {
System.err.println(“Unable to load the driver” + e);
System.exit(1);
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost/TEST","root","password");
} catch(ClassNotFoundException e) {
System.err.println(“Unable to load the driver”+ e);
System.exit(1);
} catch(SQLException e) {
System.err.println(“Cannot connect to the database”+ e);
System.exit(1);
}
Rakhi Saxena (Internet 21
Technologies)
Complete
class JDBCDemo{
Program
import static
public java.sql.*;
void main(String
args[]){ try{
Class.forName("com.mysql.jdbc.Driver")
; Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/TEST
",
"root","password");
//here TEST is the database name,
//root is the username and root is the password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from
Employees"); while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2) +"
"+rs.getString(3)+rs.getString(4));
con.close();
}catch(Exception {
e) System.out.println(e);}
}
} Rakhi Saxena (Internet 22
Technologies)
Statement objects
• Once the connection to the database is opened,
Java application creates and sends a query to
access data contained in the database.
• Three type of statement objects:
– Statement Object: Executes a query immediately
– PreparedStatement Object: Executes a compiled query
– CallableStatement Object: Executes a
stored procedure
beforeFirst() Moves the ResultSet to point before the first row in the ResultSet.
first() Moves the ResultSet to point at the first row in the ResultSet.
last() Moves the ResultSet to point at the last row in the ResultSet.
next() Moves the ResultSet to point at the next row in the ResultSet.
previous() Moves the ResultSet to point at the previous row in the ResultSet.
METHOD DESCRIPTION
refreshRow() Refreshes the column values of that row with the latest values from
the database.