DB Apps Introduction SoftUni Team Technical Trainers

Slides:



Advertisements
Similar presentations
1 JDBC Java Database Connectivity. 2 c.pdf
Advertisements

1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
Web Application Development Muhammad Ali Versonic Pte Asher Imtiaz Forman Christian College.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
CSCI 6962: Server-side Design and Programming JDBC Database Programming.
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Basics of JDBC Session 14.
1 JDBC – Java Database Connectivity CS , Spring 2010.
JDBC.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
Auto Mapping Objects SoftUni Team Database Applications
Introduction to Entity framework
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
Databases basics Course Introduction SoftUni Team Databases basics
Lec - 14.
C# Basic Syntax, Visual Studio, Console Input / Output
Introduction to MVC SoftUni Team Introduction to MVC
PHP Fundamentals Course Introduction SoftUni Team Technical Trainers
C# Database Fundamentals with Microsoft SQL Server
Introduction to Entity Framework
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
C# Databases Advanced with Microsoft SQL Server
Spring Filters Spring Interceptors SoftUni Team Spring Interceptors
EF Relations Object Composition
Entity Framework: Code First
JDBC – Java Database Connectivity
Data Definition and Data Types
Databases advanced Course Introduction SoftUni Team Databases advanced
C#/Java Web Development Basics
Web Technologies IT230 Dr Mohamed Habib.
Entity Framework: Relations
Functional Programming
MVC Architecture, Symfony Framework for PHP Web Apps
Transactions in Entity Framework
Databases Advanced Course Introduction SoftUni Team Databases Advanced
CS320 Web and Internet Programming Database Access with JDBC
Best Practices and Architecture
Best practices and architecture
How to connect natively?
Introduction to Databases
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Exporting and Importing Data
Exporting and Importing Data
Introduction to TypeScript & Angular
Spring Data Advanced Querying
/^Hel{2}o\s*World\n$/
JavaScript: ExpressJS Overview
Interacting with Database
JDBC – Java Database Connectivity
Bolat Azamat, Kim Dongmin
Using a Database with JDBC
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

DB Apps Introduction SoftUni Team Technical Trainers How to connect to a database natively (JDBC), Executing Statements, SQL Injection, Advanced Concepts - Transactions, Dao Pattern DB Apps Introduction SoftUni Team Technical Trainers Software University http://softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Table of Content JDBC Essentials Execute Statements SQL Injection Advanced Topics Transactions DAO Pattern © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Questions sli.do #db-advanced

JDBC Essentials

Java Database Connectivity (JDBC) JDBC is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with database usage: Making a connection to a database. Creating and executing SQL queries in the database. Viewing & Modifying the resulting records.

MySQL Oracle PostgreSQL JDBC Architecture APP JAVA.SQL.* DRIVER JDBC MySQL Oracle PostgreSQL SQL Server RDBMS © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Driver specifics JDBC Connection String jdbc:<driver protocol>:<connection details> JDBC URL Database JDBC URL MySQL jdbc:mysql://localhost Oracle jdbc:oracle:thin:@localhost SQL Server jdbc:sqlserver://localhost PostgreSQL jdbc:postgresql://localhost © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Driver Download MySQL Connector/J https://dev.mysql.com/downloads/connector/j/

Setup Driver IntelliJ

Connection Verification package com.company; import java.sql.*; public class Main { private static final String URL = "jdbc:mysql://localhost:3306/sys"; //Replace with your user name private static final String USER = "root"; //Replace with your password private static final String PASSWORD = "1234"; public static void main(String[] args) throws SQLException { Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); System.out.println("The connection is successful! Well done bro!"); try { // use the connection to execute queries. It may throw. } finally { try { connection.close(); } catch (SQLException e) {// log here} } JDBC URL USER PASS Connection © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Statements

JDBC Components The JDBC API provides the following interfaces and classes: DriverManager – This class manages a list of database drivers. Driver – This interface handles the communications with the database server. Connection – The connection object represents communication context. Statement – Objects used to submit the SQL statements to the database. ResultSet – These objects hold data retrieved from a database. SQLException – This class handles any errors that occur in a database application.

java.sql.* DriverManager Connection Statement ResultSet

Statements Statement PreparedStatement CallableStatement Interfaces Recommended Use Statement Used the for general-purpose access to the database. The Statement interface cannot accept parameters. PreparedStatement Used when SQL statements are used many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement Uses when database stored procedures are called. The CallableStatement interface can also accept runtime input parameters.

JDBC Statement DDL Transactions public static void main(String[] args) throws SQLException { try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) { try (Statement statement = connection.createStatement()) String sql = "CREATE TABLE students(" + "id INT PRIMARY KEY," + "name varchar(50)" + ")"; statement.executeUpdate(sql); } JDBC URL Statement SQL Execution © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

JDBC Statement DML Transactions public static void main(String[] args) throws SQLException { try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) { try (Statement statement = connection.createStatement()) String sql = "INSERT INTO students " + "VALUES(1,'Teo')"; int affectedRows = statement.executeUpdate(sql); System.out.println(affectedRows); } JDBC URL Statement SQL Execution

ResultSet The SQL statements (SELECT) that read data from a database query, return the data in a result set. The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the current row in the result set.

JDBC Statement Retrieve Data JDBC URL public static void main(String[] args) throws SQLException { try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) { try (Statement statement = connection.createStatement()) { String sql = "SELECT * FROM students"; ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println(String.format("%d, %s",id, name)); } Statement SQL Result Set Fetch Results © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

JDBC: SQL to Java Translation SQL data type Java data type Simply mappable Object mappable CHARACTER   String VARCHAR LONGVARCHAR NUMERIC java.math.BigDecimal DECIMAL BIT boolean Boolean TINYINT byte Integer SMALLINT short INTEGER int BIGINT long Long REAL float Float FLOAT double Double DOUBLE PRECISION BINARY byte[] VARBINARY LONGVARBINARY DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp

JDBC PreparedStatement public static void main(String[] args) throws SQLException { try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) { String sql = "SELECT * FROM students WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) preparedStatement.setInt(1,1); ResultSet resultSet = preparedStatement.executeQuery(); } JDBC URL SQL Prepared Statement Result Set

JDBC Parameters SQL Parameter Parameter Value Position String sql = "SELECT * FROM students WHERE id = ?"; //… preparedStatement.setInt(1,1); Parameter Parameter Value Position

JDBC CallableStatement public static void main(String[] args) throws SQLException { try (Connection connection = DriverManager. getConnection(URL, USER, PASSWORD)) { String procedure = "CALL usp_update_students (?, ?)"; try (CallableStatement callableStatement = connection.prepareCall(procedure)) callableStatement.setInt(1, 1); callableStatement.setString(2, "Teo"); callableStatement.execute(); } JDBC URL Procedure Callable Statement Add Parameters Execute © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

What is SQL Injection and How to Prevent It?

What is SQL Injection? bool login (string username, string password) { string sql = "SELECT COUNT(*) FROM users " + "WHERE username = '" + username + "' and " + “password = '" + password + "'"; try(Statement statement = connection.createStatement()) { ResultSet resultSet = statement.executeQuery(query); resultSet.next(); int numberOfUsersMatched = resultSet.getInt(1); return numberOfUsersMatched > 0; } } bool normalLogin = login ("peter", "qwerty123"); // true bool sqlInjectedLogin = login (" ' or 1=1 #", "qwerty123"); // true bool evilHackerCreatesNewUser = login ( “'; INSERT INTO users VALUES('hacker','') #", "qwerty123");

How Does SQL Injection Work? The following SQL commands are executed: Usual password check (no SQL injection): SQL-injected password check: SQL-injected INSERT command: SELECT COUNT(*) FROM users WHERE username = 'peter' and password = 'qwerty123' SELECT COUNT(*) FROM users WHERE username = ' ' or 1=1 #' and password = 'whatever' SELECT COUNT(*) FROM users WHERE username = ''; INSERT INTO users VALUES('hacker','') #' and password = 'whatever'

Preventing SQL Injection Ways to prevent the SQL injection: SQL-escape all data coming from the user: Not recommended: use as last resort only! Preferred approach: Use Prepared Statements Separate the SQL command from its arguments String escapedUsername = username.replace("'", "''"); String escapedPassword = password.replace("'", "''"); String sql = "SELECT COUNT(*) FROM users " + "WHERE username = '" + escapedUsername + "' AND " + “password= '" + escapedPassword + "'";

Prepared Statements Prevent SQL Injection bool login (string username, string password) { string sql = "SELECT COUNT(id) FROM users WHERE username = ? and password = ?"; try (PreparedStatement statement = connection. prepareStatement(query)) statement.setString(1, username); statement.setString(2, password); ResultSet resultSet = statement.executeQuery(); resultSet.next(); int numberOfUsersMatched = resultSet.getInt(1); return numberOfUsersMatched > 0;} } bool normalLogin = login ("peter", "qwerty123"); // true bool sqlInjectedLogin = login (" ' or 1=1 --", “whatever"); // false bool evilHackerCreatesNewUser = login ( "' INSERT INTO users VALUES('hacker','') --", “whatever"); //no user created

Advanced Concepts

Transactions Transaction JDBC URL Statement SQL Execute Commit public static void main(String[] args) throws SQLException{ try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) connection.setAutoCommit(false); try (Statement statement = connection.createStatement()) { String sql = "INSERT INTO students " + "VALUES(1,'Teo')"; statement.executeUpdate(sql); connection.commit(); } catch (SQLException e) { connection.rollback(); } Transaction JDBC URL Statement SQL Execute Commit Rollback © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

DAO Pattern interface use implements StudentDao + getAllStudents(): List + updateStudent(): void + deleteStudent(): void + addStudent(): void Student id: int name: String + Student() + getStudentId(): int + setStudentId(): void + getStudentName(): String + setStudentName(): void use implements StudentDaoImpl students: List + StudentDaoImpl() + getAllStudents(): List + updateStudent(): void + deleteStudent(): void + addStudent(): void © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Summary JDBC Essentials Execute Statements SQL Injection Advanced Topics Transactions DAO Pattern

DB Apps Introduction https://softuni.bg/courses/databases-advanced-hibernate © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Databases" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.