Skip to content
Open

lab #10

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
6 changes: 6 additions & 0 deletions .idea/compiler.xml

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

3 changes: 2 additions & 1 deletion .idea/encodings.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.

46 changes: 36 additions & 10 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,41 @@
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>
<!-- 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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
59 changes: 59 additions & 0 deletions src/main/java/ConnectionFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import com.mysql.cj.jdbc.exceptions.SQLError;
import com.mysql.cj.jdbc.Driver;
import java.sql.*;

public class ConnectionFactory {
//
// public static void main(String[] args) {
// getConnection();
//
// }
//
// public static final String URL = "jdbc:mysql://localhost:3306/zcwdblab?serverTimezone=UTC";
// public static final String USER = "nick";
// public static final String PASS = "password";
//
// public static Connection getConnection() {
// try {
// DriverManager.registerDriver(new Driver());
// return DriverManager.getConnection(URL, USER, PASS);
// } catch (SQLException e) {
// throw new RuntimeException("ERROR : Can't connect to the database", e);
// }
// }







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

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 void executeStatement(Connection connection, String sqlStatement) {
try {
Statement statement = getScrollableStatement(connection);
statement.execute(sqlStatement);
connection.commit();
} catch (SQLException e) {
throw new Error(e);
}
}
}
115 changes: 115 additions & 0 deletions src/main/java/MainApplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@

import com.mysql.cj.jdbc.Driver;
import daos.CarRepo;
import models.Car;

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

/**
* @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");
CarRepo<Car> carRepo = new CarRepo<>(mysqlDbConnection);
executeStatement(mysqlDbConnection, "DROP DATABASE IF EXISTS zcwdblabs;");
executeStatement(mysqlDbConnection, "CREATE DATABASE IF NOT EXISTS zcwdblabs;");
executeStatement(mysqlDbConnection, "USE zcwdblabs;");
executeStatement(mysqlDbConnection, new StringBuilder()
.append("CREATE TABLE IF NOT EXISTS car(")
.append("id int auto_increment primary key,")
.append("make varchar(255) not null,")
.append("model varchar(255) not null,")
.append("year int not null,")
.append("color varchar(255),")
.append("vin int not null);")
.toString());

carRepo.create(new Car(4, "Ford", "Ranger", 1999, "White", 491883));
carRepo.create(new Car(14, "jeep", "wrangler", 2017, "rhinogrey", 52513));
carRepo.update(14, new Car("Klondike", "Bar", 2018, "wigglenuts", 1451235));
System.out.println(carRepo.findAll());

// executeStatement(mysqlDbConnection, new StringBuilder()
// .append("INSERT INTO zcwdblabs.car(")
// .append("id, name, primary_type, secondary_type) ")
// .append("VALUES (12, 'Ivysaur', 3, 7);")
// .toString());
//
// executeStatement(mysqlDbConnection, new StringBuilder()
// .append("INSERT INTO zcwdblabs.car(")
// .append("id, name, primary_type, secondary_type) ")
// .append("VALUES (13, 'Ivysaurr', 3, 7);")
// .toString());

// String getPokemonTable = "SELECT * FROM zcwdblabs.car;";
// ResultSet resultSet = executeQuery(mysqlDbConnection, getPokemonTable);
// printResults(resultSet);
//
// String showPokemonTable = "SHOW DATABASES;";
// resultSet = executeQuery(mysqlDbConnection, showPokemonTable);
// printResults(resultSet);
}

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 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 = "nick";
String password = "password";
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);
}
}

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

import models.Car;

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

public class CarRepo<T extends Car> implements DAO<T>, ConnectionInterface {

private Connection connection;

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

public T findById(int id) {
return (T) findAll()
.stream()
.filter(car -> car.getId() == (id))
.findAny()
.get();
}

public List<Car> findAll() {
ResultSet resultSet = executeQuery("SELECT * FROM zcwdblabs.car;");
List<Car> list = new ArrayList<>();
try {
while (resultSet.next()) {
String id = resultSet.getString(1);
String make = resultSet.getString(2);
String model = resultSet.getString(3);
String year = resultSet.getString(4);
String color = resultSet.getString(5);
String vin = resultSet.getString(6);
list.add(new Car(
Integer.parseInt(id),
make,
model,
Integer.parseInt(year),
color,
Integer.parseInt(vin)));
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
return list;
}

public void update(int carId, Car dataToUpdate) {
executeStatement(String.format(new StringBuilder()
.append("UPDATE car SET make = '%s',")
.append("model = '%s',")
.append("year = %s,")
.append("color = '%s',")
.append("vin = %s ")
.append("WHERE id = %s;")
.toString(),
dataToUpdate.getMake(),
dataToUpdate.getModel(),
dataToUpdate.getYear(),
dataToUpdate.getColor(),
dataToUpdate.getVin(),
carId));
}

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

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


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