Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TeamController:
- public void create(String teamName) throws SQLException {
- Connection con = Database.getConnection();
- try {
- PreparedStatement pstmt = con.prepareStatement("INSERT INTO teams (name) VALUES (?)");
- pstmt.setString(1, teamName);
- pstmt.executeUpdate();
- } catch (SQLException e) {
- System.err.print("T." + e);
- }
- }
- public Integer findByName(String teamName) throws SQLException {
- Connection con = Database.getConnection();
- try (Statement stmt = con.createStatement()) {
- ResultSet rs = stmt.executeQuery("SELECT id FROM teams WHERE name = '" + teamName + "'");
- Integer id = rs.next() ? rs.getInt("id") : null;
- rs.close();
- return id;
- }
- }
- PlayerController
- public void create(String playerName, int teamID) throws SQLException {
- Connection con = Database.getConnection();
- try {
- PreparedStatement pstmt = con.prepareStatement("INSERT INTO players (name, team_id) VALUES (?, ?)");
- pstmt.setString(1, playerName);
- pstmt.setInt(2, teamID);
- pstmt.executeUpdate();
- } catch (SQLException e) {
- System.err.print("P." + e);
- }
- }
- /** Listeaza jucatorii unei echipe*/
- public void list(Integer teamID) throws SQLException {
- Connection con = Database.getConnection();
- try (Statement stmt = con.createStatement()) {
- ResultSet rs = stmt.executeQuery("SELECT name FROM players WHERE team_id = " + teamID);
- while(rs.next()) {
- String name = rs.getString("name");
- System.out.println(name);
- }
- }
- }
- Clasa Database: // Aici trebuie modificat cate ceva, ca nush cum e in oracleSQL
- public class Database {
- private static final String URL = "jdbc:mysql://localhost/football";
- private static final String USER = "root";
- private static final String PASSWORD = "";
- private static Connection connection = null;
- private Database() { }
- public static Connection getConnection() throws SQLException {
- if (connection == null) {
- createConnection();
- connection.setAutoCommit(false);
- }
- return connection;
- }
- public static void createConnection() {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection(URL, USER, PASSWORD);
- } catch (ClassNotFoundException e) {
- System.err.print("ClassNotFoundException: " + e);
- } catch(SQLException e) {
- System.err.println("SQLException: " + e);
- }
- }
- public static void closeConnection() {
- try {
- connection.close();
- } catch (SQLException e) {
- System.err.print("D: " + e);
- }
- }
- public static void commit() {
- try {
- connection.commit();
- } catch (SQLException e) {
- System.err.print("D: " + e);
- }
- }
- public static void rollback() {
- try {
- connection.rollback();
- } catch (SQLException e) {
- System.err.print("D: " + e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement