1
0
Fork 0

Init DB package

This commit is contained in:
Ethanell 2020-12-14 18:13:25 +01:00
parent 307c0b59eb
commit 951b7ed30a
2 changed files with 88 additions and 0 deletions

View file

@ -11,6 +11,7 @@ repositories {
dependencies {
implementation 'org.projectlombok:lombok:1.18.16'
implementation 'org.mariadb.jdbc:mariadb-java-client:2.7.1'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
}

87
src/main/java/DB/DB.java Normal file
View file

@ -0,0 +1,87 @@
package DB;
import lombok.Getter;
import java.sql.*;
public class DB {
static final private String host = "";
static final private String database = "";
static final private String user = "";
static final private String password = "";
@Getter static private Connection connection;
static public boolean connect() {
try {
if (connection == null || connection.isClosed()) {
connection = DriverManager.getConnection("jdbc:mariadb://"+host+"/"+database+"?user="+user+"&password="+password);
return true;
}
} catch (SQLException e) {
return false;
}
return false;
}
static public boolean disconnect() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
connection = null;
}
} catch (SQLException e) {
return false;
}
return false;
}
static public boolean isConnected() {
try {
if (connection != null && !connection.isClosed())
return true;
} catch (SQLException e) {
return false;
}
return false;
}
static public <T> T get(Class<T> cl, String table, String value, String check, String checkValue) {
try {
PreparedStatement ps = DB.getConnection().prepareStatement("SELECT "+value+" FROM "+table+" WHERE "+check+" = ?");
ps.setString(1, checkValue);
if (ps.execute()) {
ResultSet rs = ps.getResultSet();
rs.next();
Object returnValue;
if (cl == String.class)
returnValue = rs.getString(value);
else if (cl == Integer.class)
returnValue = rs.getInt(value);
else if (cl == Time.class)
returnValue = rs.getTime(value);
else
returnValue = rs.getObject(value);
ps.close();
return (T)returnValue;
}
} catch (SQLException e) {
return null;
}
return null;
}
static public boolean set(String table, String value, String newValue, String check, String checkValue) {
try {
PreparedStatement ps = DB.connection.prepareStatement("UPDATE "+table+" SET "+value+" = ? WHERE "+check+" = ?");
ps.setString(1, newValue);
ps.setString(2, checkValue);
int r = ps.executeUpdate();
ps.close();
if (r > 0)
return true;
} catch (SQLException e) {
return false;
}
return false;
}
}