Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySql {
private Connection conn = null;
public Statement stm = null;
public PreparedStatement pst = null;
public ResultSet rs = null;
public String Adress = "";
public String DataBase = "";
public String Username = "";
public String Password = "";
public int port = 3306;
public Connection mysql_connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(
"jdbc:mysql://"+Adress+":"+port+"/"+DataBase, ""+Username,
""+Password);
return con;
} catch (Exception e) {
System.out.println("No MySql response!");
e.printStackTrace();
return null;
}
}
public Connection getConnection() {
try {
if (conn.isClosed()) {
conn = DriverManager.getConnection(
"jdbc:mysql://"+Adress+":"+port+"/"+DataBase, ""+Username,
""+Password);
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public int tries = 0;
public void loadMySQL() {
System.out.println("Starting MySQL connection");
try {
if (conn == null || conn.isClosed()) {
conn = mysql_connect();
if (conn == null) {
System.out.println("Error connecting to mysql");
tries++;
if (tries > 5) {
//System.exit(1);
System.out.println("Too many mysql tries!");
} else {
loadMySQL();
}
}
System.out.println("Connected to MySQL!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void pingServer() {
//System.out.println("Pinging server");
try {
PreparedStatement ps = Server.mysql.getConnection().prepareStatement("select 1");
if (!ps.execute()) {
System.out.println("Error");
} else {
System.out.println("Pinging server");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}