128 lines
3.2 KiB
Java
128 lines
3.2 KiB
Java
package de.gurkengewuerz.monitoring.object;
|
|
|
|
import java.sql.*;
|
|
|
|
/**
|
|
* Created by gurkengewuerz.de on 08.04.2017.
|
|
*/
|
|
public class Database {
|
|
|
|
private String sUrl = null;
|
|
private int iTimeout = 30;
|
|
private Connection conn = null;
|
|
private Statement statement = null;
|
|
|
|
|
|
public Database(String sUrlToLoad) throws Exception {
|
|
setUrl(sUrlToLoad);
|
|
setConnection();
|
|
setStatement();
|
|
}
|
|
|
|
private void setUrl(String sUrlVar) {
|
|
sUrl = sUrlVar;
|
|
}
|
|
|
|
private void setConnection() throws Exception {
|
|
conn = DriverManager.getConnection("jdbc:sqlite:" + sUrl);
|
|
}
|
|
|
|
|
|
public Connection getConnection() {
|
|
return conn;
|
|
}
|
|
|
|
private void setStatement() throws Exception {
|
|
if (conn == null) {
|
|
setConnection();
|
|
}
|
|
statement = conn.createStatement();
|
|
statement.setQueryTimeout(iTimeout); // set timeout to 30 sec.
|
|
}
|
|
|
|
public PreparedStatement getPreparedStatement(String sql) throws SQLException {
|
|
return conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
|
|
}
|
|
|
|
public void executeUpdate(String instruction) throws SQLException {
|
|
statement.executeUpdate(instruction);
|
|
}
|
|
|
|
public ResultSet executeQuery(String instruction) throws SQLException {
|
|
return statement.executeQuery(instruction);
|
|
}
|
|
|
|
public void closeConnection() {
|
|
try {
|
|
conn.close();
|
|
} catch (Exception ignore) {
|
|
}
|
|
}
|
|
|
|
public static String escapeString(String x, boolean escapeDoubleQuotes) {
|
|
StringBuilder sBuilder = new StringBuilder(x.length() * 11 / 10);
|
|
|
|
int stringLength = x.length();
|
|
|
|
for (int i = 0; i < stringLength; ++i) {
|
|
char c = x.charAt(i);
|
|
|
|
switch (c) {
|
|
case 0: /* Must be escaped for 'mysql' */
|
|
sBuilder.append('\\');
|
|
sBuilder.append('0');
|
|
|
|
break;
|
|
|
|
case '\n': /* Must be escaped for logs */
|
|
sBuilder.append('\\');
|
|
sBuilder.append('n');
|
|
|
|
break;
|
|
|
|
case '\r':
|
|
sBuilder.append('\\');
|
|
sBuilder.append('r');
|
|
|
|
break;
|
|
|
|
case '\\':
|
|
sBuilder.append('\\');
|
|
sBuilder.append('\\');
|
|
|
|
break;
|
|
|
|
case '\'':
|
|
sBuilder.append('\\');
|
|
sBuilder.append('\'');
|
|
|
|
break;
|
|
|
|
case '"': /* Better safe than sorry */
|
|
if (escapeDoubleQuotes) {
|
|
sBuilder.append('\\');
|
|
}
|
|
|
|
sBuilder.append('"');
|
|
|
|
break;
|
|
|
|
case '\032': /* This gives problems on Win32 */
|
|
sBuilder.append('\\');
|
|
sBuilder.append('Z');
|
|
|
|
break;
|
|
|
|
case '\u00a5':
|
|
case '\u20a9':
|
|
// escape characters interpreted as backslash by mysql
|
|
// fall through
|
|
|
|
default:
|
|
sBuilder.append(c);
|
|
}
|
|
}
|
|
|
|
return sBuilder.toString();
|
|
}
|
|
} |