Java can't connect to database via SSH tunnel - java

I am developing a small java utility with which I have to retrieve data on a remote mariadb database reachable at IP_1, so the recovered data must be manipulated and saved on another database, always mariadb, on a server reachable at IP_2.
To connect to the database reachable on IP_2, using navicat, I connect in ssh to the server and then to the database as localhost. (and the connection happens correctly)
I then looked for guides on how to do this in java maven, and defined the program.
Nonetheless I can also connect correctly with Java in SSH, then when I have to communicate with the DB and open the connection, I get the following error:
java.sql.SQLNonTransientConnectionException: Socket fail to connect to host: address = (host = 192.168.100.144) (port = 3366) (type = primary). Connection refused
Do you have any suggestions or advice? I have no idea how to fix it
mycode:
App.java
package mspay.helpdesk;
/**
* Hello world!
*
*/
import java.util.*;
import java.util.Properties;
import java.io.IOException;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class App {
public static void main(String[] args) {
System.out.println("Recupero richieste di assistenza tecnica!");
// Apertura connessione SSH
try {
final JSch jsch = new JSch();
Session session = jsch.getSession("username", "IP_2", 22);
session.setPassword("password");
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL(3366, "IP_2", 3306);
if (session.isConnected()) {
System.out.println("Connessione SSH stabilita con successo!");
Class.forName("com.mysql.cj.jdbc.Driver");
Utility u = new Utility("IP_1", "user", "password", "name");
u.takeCassettiAttivi();
ResultSet ca = u.getComuni();
try {
while (ca.next()) {
System.out.println("Eleborazione del comune di: " + ca.getString(2));
u.takeRichiesteAssistenza(ca.getString(3));
ResultSet ri = u.getRichieste();
u.saveRichiesteAssistenza(ri, ca.getString(2).replace("'", " "));
}
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("Impossibile stabilire connessione SSH!");
System.exit(0);
}
} catch (JSchException jsche) {
jsche.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Class Utility.java
package mspay.helpdesk;
import java.util.*;
//gestione sql
import java.sql.*;
//gestione files
import java.nio.file.*;
import java.io.File;
import java.util.Date;
import java.time.LocalDate;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
public class Utility {
static private String host;
static private String uname;
static private String pwd;
static private String db;
static Connection c = null;
static private ResultSet ca;
static private ResultSet rich;
public Utility(String h, String usr, String pass, String database) {
host = h;
uname = usr;
pwd = pass;
db = database;
}
// recuperiamo i cassetti attivi
public void takeCassettiAttivi() {
try {
c = DriverManager.getConnection(
"jdbc:mariadb://" + host + ":3306/" + db + "?" + "user=" + uname + "&password=" + pwd + "");
String sql = "SELECT * FROM `cassetti` where abilitato = 1";
Statement st = c.createStatement();
ca = st.executeQuery(sql);
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// recuperiamo le richieste di assistenza tecnica
public void takeRichiesteAssistenza(String database) {
try {
c = DriverManager.getConnection(
"jdbc:mariadb://" + host + ":3306/" + database + "?" + "user=" + uname + "&password=" + pwd + "");
// recupero le richieste di assistenza tecnica
String sql = "SELECT * FROM `tbl_richiestatecnica` WHERE tecData BETWEEN '2022-10-19' AND '2022-10-21' ORDER BY idTEC DESC";
Statement st = c.createStatement();
rich = st.executeQuery(sql);
System.out.println("Operazione di recupero delle richieste avvenuta con successo, COMUNE DI :" + database);
c.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// salviamo le richieste sul database
public void saveRichiesteAssistenza(ResultSet richieste, String comune) {
System.out.println("Salvataggio delle richieste nel repository centrale, COMUNE DI :" + comune);
try {
String database = "dbname";
c = DriverManager.getConnection(
"jdbc:mariadb://IP_2:3366/" + database + "?user=db_user&password=db_password");
if (c.isValid(0)) {
System.out.println("Connessione al server ubuntu avvenuta con successo");
try {
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// effettuo l'insert delle richieste all'interno del DB di helpdesk
if (!comune.equals("Civitanova Marche")) {
while (richieste.next()) {
StringBuilder sql = new StringBuilder(
"INSERT INTO richieste_assistenza (comune, nominativo, cfpiva, email, oggetto, richiesta, mailcomune, datarichiesta, orarichiesta, stato) VALUES (");
sql.append("'" + comune + "', '" + richieste.getString(4).replace("'", " ") + "', '"
+ richieste.getString(5) + "', '" + richieste.getString(6) + "', '" + richieste.getString(7)
+ "', '" + richieste.getString(8) + "', '" + richieste.getString(14) + "', '"
+ richieste.getString(2) + "', '" + richieste.getString(3) + "', 'TODO')");
System.out.println("QUERY DI UPDATE");
System.out.println(sql.toString());
Statement st = c.createStatement();
st.executeUpdate(sql.toString());
}
c.close();
} else {
while (richieste.next()) {
StringBuilder sql = new StringBuilder(
"INSERT INTO richieste_assistenza (comune, nominativo, cfpiva, email, oggetto, richiesta, mailcomune, datarichiesta, orarichiesta, stato) VALUES (");
sql.append("'" + comune + "', '" + richieste.getString(4).replace("'", " ") + "', '"
+ richieste.getString(11) + "', '" + richieste.getString(5) + "', '" + richieste.getString(6)
+ "', '" + richieste.getString(7) + "', '" + richieste.getString(13) + "', '"
+ richieste.getString(2) + "', '" + richieste.getString(3) + "', 'TODO')");
System.out.println("QUERY DI UPDATE");
System.out.println(sql.toString());
Statement st = c.createStatement();
st.executeUpdate(sql.toString());
}
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getComuni() {
return ca;
}
public ResultSet getRichieste() {
return rich;
}
}

Related

REF CURSOR is not working with pgjdbc-ng driver

I am trying an example to return REFCURSOR using PGJDBC-NG Driver but getting an exception
java.lang.ClassCastException: java.lang.String cannot be cast to java.sql.ResultSet
at FunctionReturnRefCursor.main(FunctionReturnRefCursor.java:42)
Source/Code I am trying is -
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
public class FunctionReturnRefCursor {
public static void main(String[] args) throws Exception {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
Class.forName("com.impossibl.postgres.jdbc.PGDriver");
try (Connection conn = DriverManager.getConnection(
"jdbc:pgsql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try this:
import java.sql.*;
public class FunctionReturnRefCursor {
public static void main(String[] args) {
String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
+ " RETURNS refcursor "
+ " AS $$ "
+ " BEGIN "
+ " OPEN mycurs FOR select * from pg_user; "
+ " END; "
+ " $$ "
+ " LANGUAGE plpgsql";
String runFunction = "{? = call getUsers()}";
//Substituted:
Driver driver = null;
try {
driver = new com.impossibl.postgres.jdbc.PGDriver();
DriverManager.registerDriver(driver);
} catch (SQLException e) {
e.printStackTrace();
}//:Substituted
try (Connection conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/test", "postgres", "password");
Statement statement = conn.createStatement();
CallableStatement cs = conn.prepareCall(runFunction);
) {
// We must be inside a transaction for cursors to work.
conn.setAutoCommit(false);
// create function
statement.execute(createFunction);
// register output
cs.registerOutParameter(1, Types.REF_CURSOR);
// run function
cs.execute();
// get refcursor and convert it to ResultSet
ResultSet resultSet = (ResultSet) cs.getObject(1);
while (resultSet.next()) {
System.out.println(resultSet.getString("usename"));
System.out.println(resultSet.getString("passwd"));
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Data truncated for column when using FLOAT in GUI

I am using a video course on database programming with the current lesson being using Java to connect to MySQL. I have followed the video, and even copied the text working file for this particular problem (so I know the code works), but I am still getting an error. The database is to store information for books: isbn, title, author, publisher, and price. I inserted the exact same data using the command line, but when I use the program for a GUI I get a "data truncated" error. I know there are multiple answers in "data truncated" errors; however, I do not see where the data is too large, especially when inserting works using a non GUI interface. All datatypes are VARCHAR except for price which is FLOAT. The error I get is:
insert into book values('978007106789','Stuck On Java','J Reid','9.99','Osborne')
Error executing SQL
java.sql.SQLException: Data truncated for column 'price' at row 1
GUI code is:
package Connection;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class InsertRecord extends JFrame {
private JButton getBookButton, insertBookButton;
private JList bookList;
private Connection connection;
private JTextField isbn, title, author, price, publisher;
private JTextArea errorText;
public InsertRecord() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.err.println("Unable to load driver.");
System.exit(1);
}
}
public void loadBook() {
Vector<String> v = new Vector<String>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select title from book");
while (rs.next()) {
v.addElement(rs.getString("title"));
}
rs.close();
}
catch (SQLException e) {
System.err.println("Error executing SQL");
}
bookList.setListData(v);
}
private void createGUI() {
Container c = getContentPane();
c.setLayout(new FlowLayout());
bookList = new JList();
loadBook();
bookList.setVisibleRowCount(2);
JScrollPane bookListScrollPane = new JScrollPane(bookList);
getBookButton = new JButton("Get Book Title");
getBookButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String query = "select * from book where title = " +
bookList.getSelectedValue();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"select * from book where title = '"
+ bookList.getSelectedValue() + "'");
/*ResultSet rs = statement.executeQuery(
"select * from book where title = 'Java:How To Program'"); */
if (rs.next()) {
isbn.setText(rs.getString("isbn"));
title.setText(rs.getString("title"));
author.setText(rs.getString("author"));
price.setText(rs.getString("price"));
publisher.setText(rs.getString("publisher"));
}
}
catch (SQLException ex) { isbn.setText(query); }
}
}
);
insertBookButton = new JButton("Insert Book");
insertBookButton.addActionListener (
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Statement statement = connection.createStatement();
String insert = "insert into book values(";
insert += "'" + isbn.getText() + "',";
insert += "'" + title.getText() + "',";
insert += "'" + author.getText() + "',";
insert += "'" + price.getText() + "',";
insert += "'" + publisher.getText() + "')";
System.out.println(insert);
/*int i = statement.executeUpdate("insert into book values(" +
"'" + isbn.getText() + "'," +
"'" + title.getText() + "'," +
"'" + author.getText() + "'," +
"'" + price.getText() + "'," +
"'" + publisher.getText() + ")");*/
int i = statement.executeUpdate(insert);
errorText.append("Inserted " + i + " rows succcessfully.");
bookList.removeAll();
loadBook();
}
catch (SQLException ex) {
System.err.println("Error executing SQL");
ex.printStackTrace();
}
}
}
);
JPanel first = new JPanel(new GridLayout(3,1));
first.add(bookListScrollPane);
first.add(getBookButton);
first.add(insertBookButton);
isbn = new JTextField(13);
title = new JTextField(50);
author = new JTextField(50);
price = new JTextField(8);
publisher = new JTextField(50);
errorText = new JTextArea(5,15);
errorText.setEditable(false);
JPanel second = new JPanel();
second.setLayout(new GridLayout(6,1));
second.add(isbn);
second.add(title);
second.add(author);
second.add(price);
second.add(publisher);
JPanel third = new JPanel();
third.add(new JScrollPane(errorText));
c.add(first);
c.add(second);
c.add(third);
setSize(800, 400);
setVisible(true);
}
public void connectToDB() throws Exception {
//Connection conn = null;
try {
String userName = "jesse";
String password = "password";
String url = "jdbc:mysql://localhost/library";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, userName, password);
//if (conn != null) System.out.println("Database connection successful.");
}
catch (SQLException e) {
System.out.println("Can't connect to database");
System.exit(1);
}
}
private void init() throws Exception{
connectToDB();
}
public static void main(String[] args) throws Exception {
InsertRecord insert = new InsertRecord();
insert.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
insert.init();
insert.createGUI();
}
}
The insert code for simply using the command line is:
package Connection;
import java.sql.*;
import java.io.*;
public class InsertDB {
Connection connection;
public InsertDB(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.out.println("Could not load driver.");
e.printStackTrace();
}
}
public void ConnectToDB() {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/library", "jesse", "password");
System.out.println("Connected to database.");
}
catch (Exception e) {
System.out.println("Cannot connect to database.");
e.printStackTrace();
}
}
public void execSQL() {
try {
Statement stmt = connection.createStatement();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the isbn: ");
String isbn = input.readLine();
System.out.print("Enter the title: ");
String title = input.readLine();
System.out.print("Enter the author: ");
String author = input.readLine();
System.out.print("Enter the publisher: ");
String pub = input.readLine();
System.out.print("Enter the price: ");
String p = input.readLine();
double price = Double.parseDouble(p);
String insert = "Insert into book values (" + "'" + isbn + "','" + title + "','" + author + "','" + pub + "'," + price + ")";
System.out.println(insert);
int inserted = stmt.executeUpdate(insert); //returns 1 for success, 0 for failure
if (inserted > 0) {
System.out.println("Successfully inserted " + inserted + " row.");
}
}
catch (Exception e) {
System.out.println("Error executing SQL");
e.printStackTrace();
}
}
public static void main(String[] args){
InsertDB conn = new InsertDB();
conn.ConnectToDB();
conn.execSQL();
}
}
The only differences I have noticed is price being in quotes in the GUI code; however, removing the quotes simply causes the same error without quotes. Also I noticed that the GUI code sets price to 8 bits (original code was 10), whereas, float is not set to anything in MySQL (I believe I read on another post it is 8 bits by default... which is why I used 8). I reached out to the author of the video and he suggested I remove the quotes surrounding price. But as I stated this did not help... also this code was copied from his working file that worked on the video. Any help is appreciated.
Database code is:
drop table book;
create table book (
isbn_13 varchar(13) primary key,
title varchar(50),
author varchar(50),
publisher varchar(50),
price float(11)
);
Starting again from scratch I completely dropped the book table then recreated it using the MySQL code above. After recreating the table I was able to insert using the GUI code. I am not sure what the cause of my problem was, but dropping and recreating the table seemed to fix it.

How to start Derby server on the specified port by java

I tried to test Derby sample source code. Unfortunately it failed: Cannot connect Derby database: connection refused
I was told that I haven't started a server. Official tutorial:
Doesn't start any server.I have no feedback after C:\Apache\db-derby-10.4.1.3-bin\lib> java -jar derbyrun.jar server start just empty line shows and the derbyrun.jar ends.
Doesn't show how to create server on the specified port
My question is: How to start a server on the specified port so the posted code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby://localhost:1526/myDB;create=true;user=me;password=mine";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
insertRestaurants(5, "LaVals", "Berkeley");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
Setting port numbers
By default, Derby using the Network Server listens on TCP/IP port number 1527. If you want to use a different port number, you can specify it on the command line when starting the Network Server. For example:
java org.apache.derby.drda.NetworkServerControl start -p 1088
However, it is better to specify the port numbers by using any of the following methods
1. Change the startNetworkServer.bat or startNetworkServer.ksh scripts
2. Use the derby.drda.portNumber property in derby.properties
Please refer to:
https://db.apache.org/derby/docs/10.5/adminguide/tadminappssettingportnumbers.html

Connect to MySQL on Android, Driver doesn't work

I want to connect to my MySQL server, but the driver doesn't work.
How can I fix this, or what am I doing wrong? Do I need to import extra libraries (I didn't do that)?
This is my code:
public void Connection() {
String retrievedUserName = "";
String retrievedPassword = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://domainexample.com", "username", "passwoord");
PreparedStatement statement = con.prepareStatement("SELECT * FROM Gebruiker WHERE users= '" + "username" + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
retrievedUserName = result.getString("gebruikersnaam");
retrievedPassword = result.getString("password");
}
System.out.println(retrievedUserName + " passwoord = " + retrievedPassword);
} catch (Exception e) {
e.printStackTrace();
}
}

Java Server MySQL Update won't work

I recently started a big server application in java.
The problem is, that my user-update function usr.updUser(...) is not working.
First here are the files.
Server.java:
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Server extends Thread {
private ServerSocket srvSock;
SQLdb db;
User usr;
public Server(int port, SQLdb db) throws IOException{
srvSock = new ServerSocket(port);
this.db = db;
}
public void run(){
while(true){
String ret = "";
try{
Socket sock = srvSock.accept();
usr = new User(db);
DataInputStream in = new DataInputStream(sock.getInputStream());
try{
String[] cmd = in.readUTF().split(":");
switch(cmd[0]){
case "user":{
switch(cmd[1]){
case "addUser":{
ret = usr.addUser(cmd[2]);
break;
}
case "getUser":{
ret = usr.getUser(cmd[2]);
break;
}
case "updUser":{
ret = usr.updUser(cmd[2]);
break;
}
case "delUser":{
ret = usr.delUser(cmd[2]);
break;
}
}
break;
}
}
}catch(Exception e){
e.printStackTrace();
}
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeUTF(ret);
sock.close();
}catch(IOException e){
e.printStackTrace();
break;
}
}
}
public static void main(String[] args){
SQLdb db = new SQLdb("data.db");
User usr = new User(db);
if(args[0] == "new")
usr.setupTable();
usr.updUser("age=6;uid=2"));
try{
Thread server = new Server(5000, db);
server.start();
}catch(IOException e){
e.printStackTrace();
}
Thread ti = new TermInput(db);
ti.start();
Thread time = new Time(usr);
time.start();
}
}
User.java:
import java.sql.SQLException;
public class User {
SQLdb db;
String report;
public User(SQLdb db){
this.db = db;
}
public String setupTable(){
if(
db.addTable("users",
"uid INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"uname TEXT UNIQUE NOT NULL, " +
"pwd TEXT NOT NULL, " +
"mail TEXT UNIQUE NOT NULL, " +
"age INTEGER NOT NULL, " +
"rank INTEGER DEFAULT 0 , " +
"coins INTEGER DEFAULT 100 , " +
"prem INT DEFAULT 0 , " +
"setg TEXT")
)
report = "ok";
else
report = db.report;
return report;
}
public String addUser(String cmd){
try{
String[] _cmd = cmd.split(";");
if(db.addEntry("users", new String[] {"uname, pwd, mail, age",
"'" + _cmd[0] + "', '" + _cmd[1] + "', '" + _cmd[2] + "', " + _cmd[3]}))
report = "ok";
else
report = db.report;
}catch(Exception e){
report = e.getMessage();
}
return report;
}
public String getUser(String cmd){
try{
String[] _cmd = cmd.split(";");
if(db.getEntry("users", new String[] {_cmd[0], _cmd[1]})){
try{
report = "";
while(db.res.next()){
report += Integer.toString(db.res.getInt("uid")) + ";";
report += db.res.getString("uname") + ";";
report += db.res.getString("pwd") + ";";
report += db.res.getString("mail") + ";";
report += Integer.toString(db.res.getInt("age")) + ";";
report += Integer.toString(db.res.getInt("rank")) + ";";
report += Integer.toString(db.res.getInt("coins")) + ";";
report += Integer.toString(db.res.getInt("prem")) + ";";
report += db.res.getString("setg");
report += "-";
}
db.res.close();
db.stmt.close();
}catch(SQLException e){
report = e.getMessage();
}
}
}catch(Exception e){
report = e.getMessage();
}
return report;
}
public String updUser(String cmd){
try{
String[] _cmd = cmd.split(";");
if(db.updEntry("users", new String[] {_cmd[0], _cmd[1]}))
report = "ok";
else
report = db.report;
}catch(Exception e){
report = e.getMessage();
}
return report;
}
public String delUser(String cmd){
try{
if(db.delEntry("users", cmd))
report = "ok";
else
report = db.report;
}catch(Exception e){
report = e.getMessage();
}
return report;
}
}
SQLdb.java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLdb {
Connection conn;
Statement stmt;
String report;
ResultSet res;
public SQLdb(String db){
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + db);
report = "";
}catch(Exception e){
report = e.getMessage();
}
}
public boolean addTable(String table, String struct){
try{
stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE " + table + " (" + struct + ");");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean resTable(String table){
try{
stmt = conn.createStatement();
stmt.executeUpdate("DELETE FROM " + table + ";");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean delTable(String table){
try{
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE " + table + ";");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean addEntry(String table, String[] entry){
try{
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO " + table + "(" + entry[0] + ") VALUES (" + entry[1] + ");");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean getEntry(String table, String[] ident){
try{
stmt = conn.createStatement();
String exec = "SELECT " + ident[0] + " FROM " + table;
if(ident[1].equals("-")){
exec += ";";
}else{
exec += " WHERE (" + ident[1] + ");";
}
res = stmt.executeQuery(exec);
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean updEntry(String table, String[] data){
try{
stmt = conn.createStatement();
stmt.executeUpdate("UPDATE " + table + " set " + data[1] + " WHERE " + data[0] + ";");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
public boolean delEntry(String table, String entry){
try{
stmt = conn.createStatement();
stmt.executeUpdate("DELETE FROM " + table + " WHERE (" + entry + ");");
stmt.close();
report = "";
return true;
}catch(SQLException e){
report = e.getMessage();
return false;
}
}
}
TermInput.java:
import java.util.Scanner;
import java.sql.SQLException;
public class TermInput extends Thread {
Scanner s;
SQLdb sql;
public TermInput(SQLdb sql){
s = new Scanner(System.in);
this.sql = sql;
}
public void run(){
System.out.println("\nUse 'help' to get a list of available commands!\n");
boolean exit = false;
while(true){
System.out.print(">> ");
switch(s.next()){
case "help":
case "h":
case "?":{
System.out.println(
" [h]elp/[?]\tList all commands\n" +
" [s]hutdown\tShutdown the server"
);
break;
}
case "shutdown":
case "s":{
exit = true;
break;
}
case "time":{
System.out.println(Time.currentTime());
break;
}
default:{
System.out.println(
" Unknown command!\n" +
" Use 'help' to get a list of available commands!"
);
break;
}
}
if(exit) break;
}
try{
this.sql.conn.close();
}catch(SQLException e){
e.printStackTrace();
}
System.exit(0);
}
}
Time.java:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.sql.SQLException;
public class Time extends Thread{
User usr;
public Time(User usr){
this.usr = usr;
}
public void run(){
while(true){
checkTime();
}
}
private void checkTime(){
String ret = "";
ret = usr.getUser("*;-");
String[] prem = ret.split("-");
for(int x = 0; x < prem.length; x++)
System.out.println(prem[x].split(";")[7]);
}
public static int currentTime() {
int d = 0;
SimpleDateFormat s;
Calendar c = Calendar.getInstance();
s = new SimpleDateFormat("DDD");
d = (Integer.parseInt(s.format(c.getTime()))-1)*24*60*60;
s = new SimpleDateFormat("HH");
d += (Integer.parseInt(s.format(c.getTime()))-1)*60*60;
s = new SimpleDateFormat("mm");
d += (Integer.parseInt(s.format(c.getTime()))-1)*60;
s = new SimpleDateFormat("ss");
d += Integer.parseInt(s.format(c.getTime()));
return d;
}
}
You can see at Line 76 of Server.java that i want to change the Age of the User with id 2 to 6 years.
But when i make a getUser request, it isnt changed (see my time endless call function).
So why is the user isnt updated via my function?

Categories