import
java.sql.*;
public
class
GFG {
public
static
void
main(String[] args)
{
String databaseName =
"student"
;
String url
String userName =
"root"
;
String password =
"root"
;
Connection con =
null
;
Statement st =
null
;
ResultSet res =
null
;
String query =
""
;
try
{
Class.forName(
"com.mysql.jdbc.Driver"
);
con = DriverManager.getConnection(url, userName,
password);
con.setAutoCommit(
false
);
st = con.createStatement();
query
=
"INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )"
;
st.executeUpdate(query);
System.out.println(
"Inserted row 1 FIRST TIME in the table...."
);
query
=
"INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )"
;
st.executeUpdate(query);
System.out.println(
"Inserted row 2 FIRST TIME in the table...."
);
query =
"Select * from Student ; "
;
res = st.executeQuery(query);
System.out.println(
"printing data (without Rollback && without Commit )...."
);
while
(res.next())
System.out.print(res.getString(
"name"
)
+
" "
);
System.out.println();
con.rollback();
query =
"Select * from Student"
;
res = st.executeQuery(query);
System.out.println(
"printing data (with Rollback && without Commit )...."
);
boolean
empty =
true
;
while
(res.next()) {
empty =
false
;
System.out.print(res.getString(
"name"
)
+
" "
);
}
if
(empty) {
System.out.println(
"Empty table\n\n"
);
}
query
=
"INSERT INTO Student values ( 11 , 'Ram' , 'banglore' )"
;
st.executeUpdate(query);
System.out.println(
"Inserted row 1 SECOND TIME in the table...."
);
query
=
"INSERT INTO Student values ( 22 , 'Shyam' , 'Chennai' )"
;
st.executeUpdate(query);
System.out.println(
"Inserted row 2 SECOND TIME in the table...."
);
con.commit();
System.out.println(
"committed the transaction successfully...."
);
con.rollback();
System.out.println(
"Done Rollback...."
);
query =
"Select * from Student"
;
res = st.executeQuery(query);
System.out.println(
"printing data ( with Commit and then Rollback)...."
);
while
(res.next())
System.out.print(res.getString(
"name"
)
+
" "
);
System.out.println(
"\n"
);
}
catch
(ClassNotFoundException e) {
System.out.println(
"Driver Error"
);
e.printStackTrace();
}
catch
(SQLException e) {
System.out.println(
"Connection Error"
);
e.printStackTrace();
}
catch
(Exception e) {
e.printStackTrace();
}
try
{
if
(con !=
null
)
con.close();
if
(st !=
null
)
con.close();
if
(res !=
null
)
res.close();
}
catch
(Exception e) {
System.out.println(e.getMessage());
}
finally
{
System.out.println(
"Thank you ........."
);
}
}
}