Skip to content

Done #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Done #19

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.

10 changes: 10 additions & 0 deletions .idea/runConfigurations.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.

37 changes: 28 additions & 9 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,34 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.zipcoder.lab</groupId>
<artifactId>jdbcdao</artifactId>
<groupId>org.example</groupId>
<artifactId>intro-to-jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
</project>
116 changes: 116 additions & 0 deletions src/main/java/MainApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@

import com.mysql.cj.jdbc.Driver;
import daos.CarsRepository;
import models.Cars;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringJoiner;

/**
* @author git-leon
* @version 1.0.0
* @date 8/2/21 9:49 AM
*/
public class MainApplication {

public static void main(String[] args) {
registerJDBCDriver();
Connection mysqlDbConnection = getConnection("mysql");
CarsRepository carsRepository = new CarsRepository(mysqlDbConnection);
executeStatement(mysqlDbConnection, "DROP DATABASE IF EXISTS Vehicles;");
executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS Vehicles;");
executeStatement(mysqlDbConnection, "USE Vehicles;");
executeStatement(mysqlDbConnection, new StringBuilder()
.append("CREATE TABLE IF NOT EXISTS Vehicles.cars(")
.append("id int auto_increment primary key,")
.append("make text not null,")
.append("year int not null,")
.append("vin int not null,")
.append("color text null);")
.toString());

carsRepository.create(new Cars(1L, "Kia", 2016, 1891L, "red" ));
carsRepository.create(new Cars(2L, "Ford", 2004, 5678L, "purple" ));
carsRepository.create(new Cars(3L, "Toyota", 1984, 4685L, "black" ));
carsRepository.create(new Cars(4L, "Tesla", 2020, 1627L, "black" ));
carsRepository.create(new Cars(5L, "Nissan", 2010, 1467L, "silver" ));

System.out.println(carsRepository.readAll());

}

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);
}
}

static Connection getConnection(String dbVendor) {
String username = "root";
String password = "zipcode0";
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);
}
}

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

import models.Cars;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
* @author git-leon
* @version 1.0.0
* @date 8/4/21 3:05 PM
*/
public class CarsRepository implements Repo {
private Connection connection;

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

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

public void create(Cars cars) {
executeStatement(String.format(new StringBuilder()
.append("INSERT INTO Vehicles.cars(")
.append("id, make, year, vin, color) ")
.append("VALUES (%s, '%s', %s, %s, '%s');")
.toString(),
cars.getId(),
cars.getMake(),
cars.getYear(),
cars.getVin(),
cars.getColor()));
}

public List<Cars> readAll() {
ResultSet resultSet = executeQuery("SELECT * FROM Vehicles.cars;");
List<Cars> list = new ArrayList<>();
try {
while (resultSet.next()) {
String id = resultSet.getString(1);
String make = resultSet.getString(2);
String year = resultSet.getString(3);
String vin = resultSet.getString(4);
String color = resultSet.getString(5);
list.add(new Cars(
Long.parseLong(id),
make,
Integer.parseInt(year),
Long.parseLong(vin),
color));
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
return list;
}

public Cars read(Long id) {
return readAll()
.stream()
.filter(cars -> cars.getId().equals(id))
.findAny()
.get();
}

public void update(Long id, Cars newCarsData) {
executeStatement(String.format(new StringBuilder()
.append("Update cars Set make = '%s', ")
.append("make ='%s', ")
.append("year ='%s', ")
.append("vin ='%s', ")
.append("color ='%s', ")
.toString(),

newCarsData.getMake(),
newCarsData.getYear(),
newCarsData.getVin(),
newCarsData.getColor(),
id));
}

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

public void delete(Cars cars) {
delete(cars.getId());
}

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

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

/**
* @author git-leon
* @version 1.0.0
* @date 8/4/21 3:15 PM
*/
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();
}
Loading