Java examples for java.sql:h2
save User to h2 database
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class Main{ private static final String DB_CONN_URL = "jdbc:h2:file:~/h2db"; private static final String USERNAME = "surya"; private static final String PASSWORD = "kiran"; public static User saveUser(User user) { String insertQuery = "insert into users (name) values (?)"; try (Connection conn = getConnection(); PreparedStatement stmt = conn.prepareStatement(insertQuery);) { stmt.setString(1, user.getUserName()); int rows = stmt.executeUpdate(); System.out.println("User '" + user.getUserName() + "' saved. " + rows + " rows persisted to DB"); conn.commit();/*from w w w .j av a 2 s . c o m*/ } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return user; } public static Connection getConnection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); Connection conn = DriverManager.getConnection(DB_CONN_URL, USERNAME, PASSWORD); return conn; } }