package net.mc_pandacraft.java.util.mysql;

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

import org.bukkit.plugin.java.JavaPlugin;

public class DBConnection {
	JavaPlugin plugin;
	Connection conn;
	String url;
	String login;
	String pass;
	
	public DBConnection(String host, int port, String dbname, String l, String p) throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		url = "jdbc:mysql://"+host+":"+port+"/"+dbname;
		login = l;
		pass = p;
		conn = DriverManager.getConnection(url, login, pass);
		
		
	}
	
	
	public void reconnectIfNecessary() throws SQLException
	{
		try
		{
			conn.createStatement();
		}
		catch(SQLException e)
		{
			conn = DriverManager.getConnection(url, login, pass);
		}
	}
	
	public Connection getConnection() throws SQLException
	{
		if (!conn.isValid(1))
			reconnectIfNecessary();
		return conn;
	}
	
}
