[[oktatas:programozas:java:java adatbázis:mariadb|< Mariadb]] ====== MariaDB alapok ====== * **Szerző:** Sallai András * Copyright (c) 2019, Sallai András * Szerkesztve: 2019, 2020, 2023 * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]] * Web: https://szit.hu ===== Adatbázis ===== Készítsünk egy adatbázist az alábbi SQL scriptekkel: create database surubt character set utf8 collate utf8_hungarian_ci; grant all privileges on surubt.* to surubt@localhost identified by 'titok'; use surubt; create table employees ( id int not null primary key auto_increment, name varchar(50), city varchar(50), salary double, birth date ); Egy employees táblát hozunk létre, amiben az id mező értéke automatikusan generálódik. ===== Model ===== Kell egy osztály amiben tárolhatjuk egy dolgozó összes tulajdonságát. A következő mintában két konstruktort is létrehozunk, az egyikkel azonosítóval, a másikkal azonosító nélkül létrehozható egy dolgozó objektum. 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; } public Employee( String name, String city, double salary, LocalDate birth) { this.name = name; this.city = city; this.salary = salary; this.birth = birth; } } A dátumokat Java nyelven a LocalDate objektumban érdemes tárolni. ===== Beszúrás ===== Adatok beszúrására a Statement és a PreparedStatement áll rendelkezésre. A PreparedStatement osztály használata ajánlott. import java.sql.SQLException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.DriverManager; import java.time.LocalDate; class App { public static void insertEmployee(Employee employee) { Connection conn = null; try { String url = "jdbc:mariadb://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, java.sql.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); } } ==== A beszúrt rekord azonosítója ==== A prepareStatement() metódus számára adjunk át egy második paramétert, a Statement osztály egy állandóját. PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pstmt.setString(1, employee.name); pstmt.setString(2, employee.city); pstmt.setDouble(3, employee.salary); pstmt.setDate(4, java.sql.Date.valueOf(employee.birth)); pstmt.executeUpdate(); //vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ResultSet res = pstmt.getGeneratedKeys(); if (res.next()) { System.out.println(res.getInt(1)); } A pstmt objektumból így lekérdezhető a generált azonosító. ===== 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 App { public static ArrayList getEmployees() { ArrayList employeeList = new ArrayList<>(); Connection conn = null; try { String url = "jdbc:mariadb://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 employeeList; employeeList = getEmployees(); employeeList.forEach(emp -> { System.out.println(emp.name); }); } } ===== Törlés ===== import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class App { public static void deleteEmployee(int id) { Connection conn = null; try { String url = "jdbc:mariadb://localhost:3306/surubt"; conn = DriverManager.getConnection(url, "surubt", "titok"); String sql = "delete from employees where id=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); 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) throws Exception { System.out.println("Törlés"); deleteEmployee(7); } } ===== Frissítés ===== import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.time.LocalDate; public class App { public static void updateEmployee(Employee emp) { Connection conn = null; try { String url = "jdbc:mariadb://localhost:3306/surubt"; conn = DriverManager.getConnection(url, "surubt", "titok"); String sql = "update employees set " + "name=?, city=?, salary=?, birth=? "+ "where id=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, emp.name); pstmt.setString(2, emp.city); pstmt.setDouble(3, emp.salary); pstmt.setDate(4, java.sql.Date.valueOf(emp.birth)); pstmt.setInt(5, emp.id); pstmt.execute(); System.out.println("A frissítés sikeres."); }catch(SQLException ex) { System.err.println("Hiba! Az SQL művelet sikertelen!"); System.err.println(ex.getMessage()); } } public static void main(String[] args) throws Exception { System.out.println("Frissítés..."); Employee emp = new Employee( 6, "Becses Géza", "Miskolc", 391, LocalDate.parse("2000-03-22") ); updateEmployee(emp); } } ===== Fordítás parancssorból ===== javac App.java ===== Futtatás parancssorból ===== Futtatáshoz szükség van a mariadb kliens program útvonalának megadására. Ha helyben van minden: Futtatás Linuxon: java -cp .:mariadb-java-client-2.7.1.jar App Futtatás Windowson: java -cp .;mariadb-java-client-2.7.1.jar App ===== A driver ellenőrzése ===== Ha szeretnénk ellenőrizni a meghajtó osztály meglétét: Class.forName("org.mariadb.jdbc.Driver"); ===== Normál beszúrás ===== String sql2 = "insert into dolgozok" + " (nev, telepules, szuletes) values" + " ('Telepes Béla', 'Szeged', '1995-05-21')"; Statement stmt2 = conn.createStatement(); stmt2.executeQuery(sql2);