Skip to content

Instantly share code, notes, and snippets.

@cwdesautels
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwdesautels/a6e6b54b04aaa2f3d9bd to your computer and use it in GitHub Desktop.
Save cwdesautels/a6e6b54b04aaa2f3d9bd to your computer and use it in GitHub Desktop.
Using commit / rollback
package h2;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.jdbcx.JdbcDataSource;
public class H2RollbackTest
{
public static void main(String[] args)
{
Connection conn = null;
Statement stmt = null;
try
{
// H2 Driver included in build path as external lib
JdbcDataSource datasource = new JdbcDataSource();
datasource.setUrl("jdbc:h2:mem:test");
conn = datasource.getConnection("sa", "sa");
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.executeUpdate("create schema test authorization sa");
stmt.executeUpdate("create table test.a(id int primary key)");
stmt.executeUpdate("insert into test.a (id) values (0)");
stmt.executeUpdate("insert into test.a (id) values (1)");
stmt.executeUpdate("insert into test.a (id) values (2)");
stmt.executeUpdate("insert into test.a (id) values (3)");
//conn.commit();
stmt.executeUpdate("commit");
ResultSet rs = stmt.executeQuery("select * from test.a");
System.out.println("Printing seeded database");
while (rs.next())
{
System.out.println("ID [" + rs.getInt(1) + ']');
}
stmt.execute("truncate table test.a");
rs = stmt.executeQuery("select * from test.a");
System.out.println("Printing truncated database");
while (rs.next())
{
System.out.println("ID [" + rs.getInt(1) + ']');
}
stmt.executeUpdate("rollback");
stmt.executeUpdate("commit");
//conn.rollback();
//conn.commit();
rs = stmt.executeQuery("select * from test.a");
System.out.println("Printing rolled back database");
while (rs.next())
{
System.out.println("ID [" + rs.getInt(1) + ']');
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (stmt != null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment