< MySQL

Java MySQL - Kezdés

Szerző: Sallai András

Copyright © 2023, Sallai András

Licenc: CC BY-SA 4.0

Web: https://szit.hu

A modell

import java.time.LocalDate; public class Employee { Integer id; String name; String city; double salary; LocalDate birth; public Employee( Integer id, String name, String city, double salary, LocalDate birth) { this.id = id; this.name = name; this.city = city; this.salary = salary; this.birth = birth; } }

Beszúrás

import java.sql.SQLException; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.DriverManager; import java.time.LocalDate; class Program01 { public static void insertEmployee(Employee employee) { Connection conn = null; try { String url = "jdbc:mysql://localhost:3306/surubt"; conn = DriverManager.getConnection(url, "surubt", "titok"); String sql = "insert into employees" + " (name, city, salary, birth) values" + " (?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, employee.name); pstmt.setString(2, employee.city); pstmt.setDouble(3, employee.salary); pstmt.setDate(4, Date.valueOf(employee.birth)); pstmt.execute(); }catch(SQLException ex) { System.err.println("Hiba! Az SQL művelet sikertelen!"); System.err.println(ex.getMessage()); } } public static void main(String[] args) { Employee emp = new Employee( 1, "Csendes Emese", "Szolnok", 345, LocalDate.parse("2002-05-15") ); insertEmployee(emp); } }

Lekérdezés

import java.sql.SQLException; import java.sql.Statement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.DriverManager; import java.util.ArrayList; class Program01 { public static ArrayList<Employee> getEmployees() { ArrayList<Employee> employeeList = new ArrayList<>(); Connection conn = null; try { String url = "jdbc:mysql://localhost:3306/surubt"; conn = DriverManager.getConnection(url, "surubt", "titok"); String sql = "select * from employees"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { Employee emp = new Employee( rs.getInt("id"), rs.getString("name"), rs.getString("city"), rs.getDouble("salary"), rs.getDate("birth").toLocalDate() ); employeeList.add(emp); } }catch(SQLException ex) { System.err.println("Hiba! Az SQL művelet sikertelen!"); System.err.println(ex.getMessage()); } return employeeList; } public static void main(String[] args) { ArrayList<Employee> employeeList; employeeList = getEmployees(); employeeList.forEach(emp -> { System.out.println(emp.name); }); } }