Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package domino.server;
- import java.rmi.RemoteException;
- import java.rmi.server.UnicastRemoteObject;
- import java.util.ArrayList;
- import java.util.List;
- 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 domino.DominoStorageIface;
- public class DominoStorageImpl extends UnicastRemoteObject implements DominoStorageIface {
- Connection conn;
- protected DominoStorageImpl(String s) throws Exception {
- String user = "sa";
- String password = "";
- String url = "jdbc:hsqldb:file:" + s;
- loadDbDriver("org.hsqldb.jdbc.JDBCDriver");
- conn = DriverManager.getConnection(url, user, password);
- createTables(conn);
- }
- // TODO Auto-generated constructor stub
- private static void loadDbDriver(String driverClassName) throws Exception {
- try {
- Class.forName(driverClassName);
- } catch (Exception e) {
- System.err.println("ERROR: failed to load JDBC driver.");
- throw e;
- }
- }
- private static void createTables(Connection conn) throws SQLException {
- try (Statement stat = conn.createStatement();) {
- stat.executeUpdate("drop table if exists Dominos;");
- stat.executeUpdate("create table Dominos (name varchar(80), Domino varchar(20), idx int);");
- }
- }
- @Override
- public void save(String userName, List<String> dominos) throws RemoteException {
- try (PreparedStatement st = conn.prepareStatement("DELETE FROM Dominos WHERE name = ?;");) {
- st.setString(1, userName);
- st.executeUpdate();
- } catch (SQLException exc) {
- System.out.println(exc.getMessage());
- }
- for (int i = 0; i < dominos.size(); i++) {
- try (PreparedStatement st = conn.prepareStatement("INSERT INTO Dominos (name, Domino, idx) VALUES (?, ?, ?);");) {
- addDomino(st, userName, dominos.get(i), i + 1);
- st.executeUpdate();
- } catch (SQLException exc) {
- System.out.println(exc.getMessage());
- }
- }
- }
- private static void addDomino(PreparedStatement prep, String name, String domino, int idx) {
- try {
- prep.setString(1, name);
- prep.setString(2, domino);
- prep.setInt(3, idx);
- prep.addBatch();
- } catch (SQLException exc) {
- System.out.println(exc.getMessage());
- }
- }
- @Override
- public List<String> load(String userName) throws RemoteException {
- List<String> dominos = new ArrayList<>();
- String domino = "";
- try (Statement stat = conn.createStatement();
- ResultSet rs = stat.executeQuery("select * from Domino where name = userName;");) {
- while (rs.next()) {
- String name = rs.getString("userName");
- System.out.printf("domino = %s", domino);
- dominos.add(domino);
- }
- } catch (SQLException exc) {
- System.out.println(exc.getMessage());
- }
- return dominos;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement