נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
39
חלקPart 7: Java בעולם האמיתיJava in the real world כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

JDBC ו-HttpClientJDBC & HttpClient

מסד נתונים עם JDBC ו-SQL, PreparedStatement, וקריאות HTTP עם HttpClient.

A database with JDBC and SQL, PreparedStatement, and HTTP calls with HttpClient.

או Ctrl+Por Ctrl+P

הנקודות החשובותKey points

  • JDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים:JDBC: Java's standard way to talk to a database:
  • SQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (' OR '1'='1).SQL injection: When user input is glued into an SQL string, the input can change the query (' OR '1'='1).
  • חיבור, יצירת טבלה, הכנסה ושאילתה.A connection, creating a table, an insert and a query.
  • כל ערך נכנס דרך ? ו-setString/setInt, אף פעם לא בחיבור מחרוזות.Every value goes in through ? and setString/setInt, never by gluing strings.
  • כדי להריץ באמת, התוכנית מרימה שרת HTTP קטן על המחשב עצמו (HttpServer מה-JDK), ואז שולחת אליו בקשות עם HttpClient.To really run, the program starts a tiny HTTP server on the machine itself (HttpServer from the JDK), then sends it requests with HttpClient.
  • הפלט אמיתי מזמן הבנייה.The output is real, from build time.
  • main מדבר רק עם BookRepository.main talks only to BookRepository.
  • היום המימוש בזיכרון; מחר JdbcBookRepository עם הקוד מהתזכורת הראשונה, בלי לשנות שורה ב-main.Today the implementation is in memory; tomorrow a JdbcBookRepository with the code from the first refresher, without changing a line of main.
  • מדף, צעד 39: המדף מעל RepositoryShelf, step 39: the shelf over a Repository

מונחיםTerms

  • JDBCJDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים: DriverManager.getConnection, PreparedStatement, ResultSet. כל מסד (PostgreSQL, MySQL, H2) מגיע עם driver משלו.Java's standard way to talk to a database: DriverManager.getConnection, PreparedStatement, ResultSet. Each database (PostgreSQL, MySQL, H2) comes with its own driver.
  • SQL injectionSQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (' OR '1'='1). פרמטרים (?) שולחים את הקלט בנפרד, כנתון ולא כקוד.When user input is glued into an SQL string, the input can change the query (' OR '1'='1). Parameters (?) send the input separately, as data and not as code.
  • RepositoryRepository: interface שמסתיר איפה הנתונים נשמרים (save, findByAuthor). מימוש אחד מדבר עם מסד נתונים, ואחר שומר בזיכרון לבדיקות.An interface hiding where data is kept (save, findByAuthor). One implementation talks to a database, another keeps it in memory for tests.
  • HttpClientHttpClient: HttpClient.newHttpClient() ו-client.send(request, BodyHandlers.ofString()): שולח בקשת HTTP ומחזיר HttpResponse עם statusCode(), headers() ו-body().HttpClient.newHttpClient() and client.send(request, BodyHandlers.ofString()): sends an HTTP request and returns an HttpResponse with statusCode(), headers() and body().
  • קוד סטטוסstatus code: מספר בתשובת HTTP: 200 הצליח, 201 נוצר, 400 בקשה שגויה, 404 לא נמצא, 500 שגיאת שרת.A number in an HTTP response: 200 OK, 201 created, 400 bad request, 404 not found, 500 server error.
  • JDBCJDBC: הדרך הסטנדרטית של Java לדבר עם מסד נתונים: DriverManager.getConnection, PreparedStatement, ResultSet. כל מסד (PostgreSQL, MySQL, H2) מגיע עם driver משלו.Java's standard way to talk to a database: DriverManager.getConnection, PreparedStatement, ResultSet. Each database (PostgreSQL, MySQL, H2) comes with its own driver.
  • SQL injectionSQL injection: כשמחברים קלט של משתמש לתוך מחרוזת SQL, הקלט יכול לשנות את השאילתה (' OR '1'='1). פרמטרים (?) שולחים את הקלט בנפרד, כנתון ולא כקוד.When user input is glued into an SQL string, the input can change the query (' OR '1'='1). Parameters (?) send the input separately, as data and not as code.
  • RepositoryRepository: interface שמסתיר איפה הנתונים נשמרים (save, findByAuthor). מימוש אחד מדבר עם מסד נתונים, ואחר שומר בזיכרון לבדיקות.An interface hiding where data is kept (save, findByAuthor). One implementation talks to a database, another keeps it in memory for tests.
  • HttpClientHttpClient: HttpClient.newHttpClient() ו-client.send(request, BodyHandlers.ofString()): שולח בקשת HTTP ומחזיר HttpResponse עם statusCode(), headers() ו-body().HttpClient.newHttpClient() and client.send(request, BodyHandlers.ofString()): sends an HTTP request and returns an HttpResponse with statusCode(), headers() and body().
  • קוד סטטוסstatus code: מספר בתשובת HTTP: 200 הצליח, 201 נוצר, 400 בקשה שגויה, 404 לא נמצא, 500 שגיאת שרת.A number in an HTTP response: 200 OK, 201 created, 400 bad request, 404 not found, 500 server error.

Cheatsheet

JDBC עם PreparedStatementJDBC with PreparedStatement
try (Connection db = DriverManager.getConnection("jdbc:h2:mem:shelf")) {
    db.createStatement().execute("CREATE TABLE book (title VARCHAR(100), author VARCHAR(100), year INT)");
    try (PreparedStatement insert = db.prepareStatement("INSERT INTO book VALUES (?, ?, ?)")) {
        insert.setString(1, "Dune");
        insert.setString(2, "Herbert");
        insert.setInt(3, 1965);
        insert.executeUpdate();
    }
    try (PreparedStatement q = db.prepareStatement("SELECT title, year FROM book WHERE author = ?")) {
        q.setString(1, "Herbert");
HttpClient מול שרת קטןHttpClient against a tiny server
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/books/1", ex -> {
    byte[] body = "{\"title\": \"Dune\", \"year\": 1965}".getBytes();
    ex.getResponseHeaders().add("Content-Type", "application/json");
    ex.sendResponseHeaders(200, body.length);
    ex.getResponseBody().write(body);
    ex.close();
});
server.start();
String base = "http://127.0.0.1:" + server.getAddress().getPort();
Repository: הנתונים מאחורי interfaceRepository: data behind an interface
BookRepository repo = new InMemoryBookRepository();
repo.save(new Book("Emma", "Austen", 1815));
repo.save(new Book("Dune", "Herbert", 1965));
repo.save(new Book("Persuasion", "Austen", 1817));
System.out.println(repo.findByAuthor("Austen"));
System.out.println(repo.findByTitle("Hamlet").isPresent());

שגיאות שפגשנוErrors we met

שגיאהErrorמה זה אומרWhat it meansמה עושיםWhat to do

נבנה על ידיBuilt by Ariel Yohimovich