Databases

The Story of How Debbie Used the Power of Friendship to Take Home Gold at Her Local Hackathon

By Drew Lopreiato

Prologue

Walt Walt
Debbie Debbie Day Taybass
Yalenchka Yalenchka

Fiona Fiona
Yusa Yusa
Seth Seth
Vance Adjunct Professor Vance

Quick Outline

  • When to use a database
  • What a database is
  • How to use a database
  • Common Database Patterns
  • Security Practices
  • Advanced SQL Queries

Please Ask Questions!

"Why did you choose to talk about databases?"

"Yo this shit looks fly as fuck."

"God, when is this over?"

Y Yalenchka 'Y' Burdukovskychev

"Y, Why do I need a database?"

Why You Might Need a Database

A good interface for structured data

Finds data you want quickly

Built to work over networks

Y Walt Isa

"Walt Isa database?"

What a Database Is

In essence, a database is a file with different interface.

File

  • Read, Write, Seek
  • Character/Line Granularity
  • No Pre-defined Structure

Database

  • Create, Read, Update, Delete
  • Datatype Granularity
  • Row Column Structure

Consider This Object


class AcmMember {
    string Name;
    Date GraduationDate;
    int MeetingsAttended;
    BihemisphericDecaoctant BroomballPosition;
}
            

Broomball

OCTOBER 9TH

BihemisphereicDecaoctant Definition


enum BihemisphereicDecaoctant {OffenseRight, OffenseLeft, OffensePost,
        AlphaOuterRight, AlphaInnerRight, AlphaInnerLeft, AlphaOuterLeft,
        AlphaNuetralLeft, AlphaNuetralRight, BetaNuetralRight,
        BetaNuetralLeft, BetaOuterLeft, BetaInnerLeft, BetaInnerRight,
        BetaOuterRight, DefenseGoal, DefenseLeft, DefenseRight};
            

Game plan available after today's talk

Serialization

File


{
  "Name" : "Nick",
  "GraduationDate" : "5/6/16",
  "MeetingsAttended" : 30,
  "BihemisphericDecaoctant"
    : "AlphaOuterRight"
}
                

Database

+-----+--------+----+----------------+
|Name |GradDate|M.A.| BhmsphrcDcctnt |
+-----+--------+----+----------------+
|Nick | 5/6/16 | 30 | AlphaOuterRight|
+-----+--------+----+----------------+
                

Serialization

File


{
  "Name" : "Nick",
  "GraduationDate" : "5/6/16",
  "MeetingsAttended" : 30,
  "BihemisphericDecaoctant"
    : "AlphaOuterRight"
},
{
  "Name" : "Alice",
  "GraduationDate" : "5/6/16",
  "MeetingsAttended" : 2,
  "BihemisphericDecaoctant"
    : "DefenseGoal"
}
                

Database

+-----+--------+----+----------------+
|Name |GradDate|M.A.| BhmsphrcDcctnt |
+-----+--------+----+----------------+
|Nick | 5/6/16 | 30 | AlphaOuterRight|
+-----+--------+----+----------------+
|Alice| 5/6/18 | 15 |   DefenseGoal  |
+-----+--------+----+----------------+
                

Y Yusa "Data" Bass

"How do I Yusa 'Data' Bass?"

How to Set Up Your Database

Webserver Setup
Client/Server Setup

Connecting to Your Database


$databaseObject = new mysqli('lopreiato.us', 'drew',
    'pa$$w0rd', 'acm_presentation');

Connection conn = DriverManager.getConnection(
    "jdbc:mysql://lopreiato.us/acm_presentation", "drew", "pa$$w0rd");

MySQL.Data.MySqlClient.MySqlConnection conn;
conn = new MySql.Data.MySqlClient.MySqlConnection(
    "server=lopreiato.us;uid=drew;pwd=pa$$w0rd;database=acm_presentation;";

MYSQL *con = mysql_init(NULL);
mysql_real_connect(con, "lopreiato.us", "drew", "pa$$w0rd",
    NULL, 0, NULL, 0);
            

Basic Operations

Create INSERT
Read SELECT
Update UPDATE
Delete DELETE

Consider Table "acm_members"

name graduation meetingsAttended bhmsphrcDcctnt
Nick 2016-05-06 30 AlphaOuterRight
Alice 2018-05-06 15 DefenseGoal

INSERT INTO acm_members (name, graduation, meetingsAttended, bhmsphrcDcctnt)
VALUES ('John', '2017-05-06', 0, 'BetaNuetralRight');
            
name graduation meetingsAttended bhmsphrcDcctnt
Nick 2016-05-06 30 AlphaOuterRight
Alice 2018-05-06 15 DefenseGoal
John 2017-05-06 0 BetaNuetralRight

DELETE FROM acm_members
WHERE name='John';
            
name graduation meetingsAttended bhmsphrcDcctnt
Nick 2016-05-06 30 AlphaOuterRight
Alice 2018-05-06 15 DefenseGoal

UPDATE acm_members
SET meetingsAttended=meetingsAttended-1
WHERE name='Nick';
            
name graduation meetingsAttended bhmsphrcDcctnt
Nick 2016-05-06 29 AlphaOuterRight
Alice 2018-05-06 15 DefenseGoal

SELECT name, graduation
FROM acm_members
WHERE meetingsAttended > 0;
            

RETURN VALUE

name graduation
Nick 2016-05-06
Alice 2018-05-06

Designing Our Trivia Game

  • Sign In
  • Answer Questions
  • See a Leader Board

Designed In Java


class User {
  string Name;
  int Score;
}
class Question {
  string Question;
  string Answer;
}
class Game {
  ArrayList<User> Users;
  ArrayList<Question> Questions;
}
            

Designed In SQL

Name Score
varchar(32) int(10)
Question Answer
varchar(128) varchar(32)
Fiona Fiona Keys

Primary Keys

Has to be Unique

Data is Clustered Based on this Value

User Feedback!

"Wow! This app is fun, but how am I am supposed to know about all this random stuff? I only got 3." "Jeez, I wish I could at least have a chance at some of these questions." "GG2EZ SCRUBLORDS. GET REKT M8! LOLOLOLOL"

Y F. Orin Keys

Foreign Keys

  • Save Space
  • Easy Updates
  • Keep All Values in One Spot

Storing Arrays

For storing data in the...

SECOND DIMENSION


class CategoryScore {
  int Category; // the primary key of the category
  int Score; // the score the user earned
}
class Person {
  int ID;
  string name;
  ArrayList<CategoryScore> Scores;
}
class Game {
  ArrayList<Person> Users;
}
            

Mapping Table

Y Seth Querity

"Sounds like you need help with Seth Querity!"

Log In Systems

1.) Username should be unique

FOR THE LOVE OF ALL THAT IS HOLY

DO NOT STORE PASSWORDS AS PLAIN TEXT

EVER

EVER

EVER

EVER

EVER

EVER

Password Hashing!


function Register(string Username, string Password) {
  string HashValue = hash(Password);

  string registerUserQuery = "INSERT INTO users (username, password)" +
    "VALUES ('" + Username + "', '" + HashValue + "');";

  SqlConnection.query(registerUserQuery);
}
          

INSERT INTO users (username, hashed_password)
VALUES ('Seth', 'aa21e1e64b5ca4f6e7bd20ed945b8b79');
          

How do I Authenticate?


function boolean Authenticate(string Username, string Password) {
  string HashValue = hash(Password);

  string authQuery = "SELECT * FROM trivia_users WHERE username='" + username
    + "' AND hashed_password='" + HashValue + "'";

  SqlResult userSelect = SqlConnection.query(authQuery);

  return userSelect.num_rows > 0;
}
          

SELECT * FROM trivia_users 
WHERE username='Seth' AND hashed_password='aa21e1e64b5ca4f6e7bd20ed945b8b79';
          
Y "2:23 Breh!"

"THE SHOW CASE STARTS IN 7 MINUTES!" Debbie

The Database is empty.

How?

A SQL Injection

Why?

Someone wanted to break your project

Who?

Arun.

A SQL Injection


function Register(string Username, string Password) {
  string HashValue = hash(Password);

  string registerUserQuery = "INSERT INTO users (username, password)" +
    "VALUES ('" + Username + "', '" + "HashValue');";

  SqlConnection.query(registerUserQuery);
}
            

Register("Seth", "PurpleMonkeyDishwasher");
INSERT INTO users (username, hashed_password)
VALUES ('Seth', 'aa21e1e64b5ca4f6e7bd20ed945b8b79');
            

void Register("Seth', ''); DROP TABLE trivia_questions; --", "LOLHAX");

INSERT INTO users (username, hashed_password)
VALUES ('Seth', ''); DROP TABLE trivia_questions; --', '6978ab23a8f309433addd76793a55ddf');
            

Always Use Protection

Determine What's Valid

  • Deny All Unacceptable Strings
  • Escape All Strings Before Entry to Database
  • Escape All Strings Before Display on Webpage


What is you're name? What is you\'re name?
Who's dog is this? Who\'s dog is this?
All my corgi's are brown. All my corgi\'s are brown.

A Failed SQL Injection


void Register(string Username, string Password) {
  // ...
  Username.replace("'", "\'");
  // ...
}
            

void Register("Seth', ''); DROP TABLE trivia_questions; --", "LOLHAX");

INSERT INTO users (username, hashed_password)
VALUES ('Seth\', \'\'); DROP TABLE trivia_questions; --', '6978ab23a8f309433addd76793a55ddf');
            

The Results are In...

In First place...

DEBBIE DAY TAYBASS

Y

But our story doesn't end here.

Y Ad. Vance Seaqual-Kweries

"Can you help me optimize my game with Ad. Vance Seaqual-Kweries?"

The High Score Table


ArrayList<Triple<String, Category, int>> GetHighScoreTable(int UserScore, int Radius) {
    ArrayList<Triple<String, Category, int>> highScoreTable =
      new ArrayList<Triple<String, Category, int>>();

    int UpperBound = UserScore + Radius;
    int LowerBound = UserScore - Radius;

    String selectScoresQuery = "SELECT * FROM trivia_scores WHERE score<=" + UpperBound
      + " AND score>=" + LowerBound + ";";
    SqlResult nearbyScores = SqlConnection.query(selectScoresQuery);

    String selectCategoriesQuery = "SELECT * FROM trivia_categories;";
    SqlResult categories = SqlConnection.query(selectCategoriesQuery);

    foreach (Score in nearbyScores) {
      String getUserNameQuery = "SELECT first_name FROM triva_users WHERE id=" + Score.user_id + ";";

      SqlResult userName = SqlConnection.query(getUserNameQuery);

      String category = categories[Score.category_id];

      highScoreTable.add(new Triple(userName.first_name, category, Score.score));
    }

    return highScoreTable;
}
          

Joins

Inner Join

Inner Join

Excludes any non-matched data

Left Join

Left Join

Guarantees the existance of every row from the left
Anything unmatched will be given value NULL

Right Join

Right Join

Guarantees the existance of every row from the right
Anything unmatched will be given value NULL

Full/Outer Join

Outer Join

Guarantees the existance of every row
Anything unmatched will be given value NULL

Calculating Ranking


int GetRank(int UserScore, int Category) {
  String selectUsersQuery = "SELECT user_id FROM trivia_scores WHERE score <= "
    + UserScore + " AND category_id=" + Category + ";";

  SqlResult betterUsers = SqlConnection.query(selectUsersQuery);

  int count = 0;
  foreach (User in BetterUsers) {
    count++;
  }

  return count;
}
          

Aggregations


SELECT count(*)
FROM trivia_scores
WHERE category_id=5;
          

Returns 1 Row

Thank you

Visit my Github for the source where I left more comments.
http://github.com/dLopreiato

Made with reveal.js

Character Design by Emma

In loving memory of Noah Sequil

Noah