Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .idea/compiler.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions .idea/jarRepositories.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 19 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,29 @@
<groupId>com.zipcoder.lab</groupId>
<artifactId>jdbcdao</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
</dependencies>
</project>
121 changes: 121 additions & 0 deletions src/main/java/MainApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import daos.StudentRepository;
import models.Student;

import com.mysql.jdbc.Driver;
import java.sql.*;
import java.time.LocalDate;
import java.util.StringJoiner;

public class MainApplication {

public static void main(String[] args) {
registerJDBCDriver();
Connection mysqlDbConnection = getConnection("mysql");
StudentRepository studentRepository = new StudentRepository(mysqlDbConnection);
executeStatement(mysqlDbConnection, "DROP DATABASE IF EXISTS IAODataTest;");
executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS IAODataTest;");
executeStatement(mysqlDbConnection, "USE IAODataTest;");
executeStatement(mysqlDbConnection, new StringBuilder()
.append("CREATE TABLE IF NOT EXISTS IAODataTest.students(")
.append("id int auto_increment primary key,")
.append("name text not null,")
.append("grade int not null,")
.append("school text,")
.append("dob DATE,")
.append("age int);")
.toString());

studentRepository.create(new Student(10L, "Thai", 3, "Sanford", LocalDate.of(2011, 11, 11)));
studentRepository.create(new Student(11L, "Tyson", 6, "Kirk Middle", LocalDate.of(2009, 4,17)));
studentRepository.create(new Student(12L, "Amira", 1, "Sanford", LocalDate.of(2014, 1,3)));
studentRepository.create(new Student(13L, "David", 3, "New Castle Charter", LocalDate.of(2011, 3, 27)));
studentRepository.create(new Student(16L, "Kassidy", 10, "Ursuline Academy", LocalDate.of(2005, 5,20)));
studentRepository.create(new Student(15L, "Meadow", 6, "Talley Middle", LocalDate.of(2009, 12, 13)));
studentRepository.create(new Student (19L, "Arden", 3, "Hanby Elementary", LocalDate.of(2011, 10, 1)));
System.out.println(studentRepository.readAll());
Student arden = new Student (19L, "Arden", 3, "Hanby Elementary");
studentRepository.delete(15L);
studentRepository.delete(arden);
Student kassidy = new Student(16L, "Kassidy", 10, "Ursuline Academy");
Student david = new Student(13L, "David", 3, "New Castle Charter", LocalDate.of(2011, 3, 27));
studentRepository.updateId(17L, kassidy);
studentRepository.updateBirthday(LocalDate.of(2010, 10, 10), david);
System.out.println(studentRepository.readAll());
System.out.println(studentRepository.read(17L));
System.out.println(studentRepository.read(13L));

}

static ResultSet executeQuery(Connection connection, String sqlQuery) {
try {
Statement statement = getScrollableStatement(connection);
return statement.executeQuery(sqlQuery);
} catch (SQLException e) {
throw new Error(e);
}
}

static void printResults(ResultSet resultSet) {
try {
for (int rowNumber = 0; resultSet.next(); rowNumber++) {
String firstColumnData = resultSet.getString(1);
String secondColumnData = resultSet.getString(2);
String thirdColumnData = resultSet.getString(3);
System.out.println(new StringJoiner("\n")
.add("Row number = " + rowNumber)
.add("First Column = " + firstColumnData)
.add("Second Column = " + secondColumnData)
.add("Third column = " + thirdColumnData));
}
} catch (SQLException e) {
throw new Error(e);
}
}

static void executeStatement(Connection connection, String sqlStatement) {
try {
Statement statement = getScrollableStatement(connection);
statement.execute(sqlStatement);
} catch (SQLException e) {
throw new Error(e);
}
}

static Statement getScrollableStatement(Connection connection) {
int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
try { // scrollable statements can be iterated more than once without closing
return connection.createStatement(resultSetType, resultSetConcurrency);
} catch (SQLException e) {
throw new Error(e);
}
}


//change root name and password to local info
static Connection getConnection(String dbVendor) {
String username = "root";
String password = "pw";
String url = new StringBuilder()
.append("jdbc:")
.append(dbVendor)
.append("://127.0.0.1/")
.append("?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC")
.toString();
try {
return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
throw new Error(e);
}
}

static void registerJDBCDriver() {
// Attempt to register JDBC Driver
try {
DriverManager.registerDriver(Driver.class.newInstance());
} catch (InstantiationException | IllegalAccessException | SQLException e1) {
throw new RuntimeException(e1);
}
}

}
39 changes: 39 additions & 0 deletions src/main/java/daos/Repo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package daos;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public interface Repo {
default void executeStatement(String sqlStatement) {
try {
Statement statement = getScrollableStatement();
statement.execute(sqlStatement);
} catch (SQLException e) {
throw new Error(e);
}
}

default Statement getScrollableStatement() {
int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
int resultSetConcurrency = ResultSet.CONCUR_READ_ONLY;
try { // scrollable statements can be iterated more than once without closing
return getConnection().createStatement(resultSetType, resultSetConcurrency);
} catch (SQLException e) {
throw new Error(e);
}
}

default ResultSet executeQuery(String sqlQuery) {
try {
Statement statement = getScrollableStatement();
return statement.executeQuery(sqlQuery);
} catch (SQLException e) {
throw new Error(e);
}
}

Connection getConnection();

}
149 changes: 149 additions & 0 deletions src/main/java/daos/StudentRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package daos;

import models.Student;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class StudentRepository implements Repo{

private Connection connection;

public StudentRepository(Connection connection) {
this.connection = connection;
}

@Override
public Connection getConnection() {
return connection;
}

public void create(Student student) {
executeStatement(String.format(new StringBuilder()
.append("INSERT INTO IAODataTest.students(")
.append("id, name, grade, school, DOB, age) ")
.append("VALUES (%s, '%s', %s, '%s', DATE '%s', %s);")
.toString(),
student.getId(),
student.getName(),
student.getGrade(),
student.getSchool(),
student.getDateOfBirthSQLString(),
student.getAge())); //age will appear in table but not in resultSet;
}

public List<Student> readAll() {
ResultSet resultSet = executeQuery("SELECT * FROM IAODataTest.students;");
List<Student> list = new ArrayList<>();
try {
while (resultSet.next()) {
String id = resultSet.getString(1);
String name = resultSet.getString(2);
String grade = resultSet.getString(3);
String school = resultSet.getString(4);
String dob = resultSet.getString(5);
String age = resultSet.getString(6);
list.add(new Student (
Long.parseLong(id),
name,
Integer.parseInt(grade),
school,
LocalDate.parse(dob),
Integer.parseInt(age)));
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
return list;
}


public Student read(Long studentId) {
return readAll()
.stream()
.filter(student -> student.getId().equals(studentId))
.findAny()
.get();
}

public void updateId(Long newId, Student newStudentData) {
Long reset = newId;
Long find = newStudentData.getId();
executeStatement(String.format(new StringBuilder()
.append("UPDATE students ")
.append("SET id = %s ")
.append("WHERE id = %s;")
.toString(),
reset,
find));


}

public void updateSchool(String newSchool, Student newStudentData){
String reset = newSchool;
Long find = newStudentData.getId();
executeStatement(String.format(new StringBuilder()
.append("UPDATE students ")
.append("SET school = '%s' ")
.append("WHERE id = %s;")
.toString(),
reset,
find));

}

public void updateBirthday(LocalDate date, Student newStudentData){
String reset = getDOBString(date);
Long find = newStudentData.getId();
executeStatement(String.format(new StringBuilder()
.append("UPDATE students ")
.append("SET dob = DATE '%s' ")
.append("WHERE id = %s;")
.toString(),
reset,
find));

}

public String getDOBString(LocalDate date){
String joined = "";
int year = date.getYear();
int month = date.getMonthValue();
int day = date.getDayOfMonth();

if (month < 10 && day < 10){
joined = String.format("%s-0%s-0%s", year, month, day);
} else if (month < 10){
joined = String.format("%s-0%d-%s", year, month, day);
} else if (day < 10) {
joined = String.format("%s-%s-0%s", year, month, day);
} else

joined = String.format("%s-%s-%s", year, month, day);


return joined;

}

public void delete(Long id) {
Long deleteThis = id;
executeStatement(String.format(new StringBuilder()
.append("DELETE FROM students WHERE id = %s;")
.toString(),
id));

}

public void delete(Student student) {
Long find = student.getId();
delete(find);

}
}
Loading