Ir para conteúdo
  • 0

MySQL - Tão difícil assim?


Ducky

Pergunta

Olá, estou tentando conectar o MySQL a um plugin teste que estou fazendo..

 

Eu estava usando em si, o código MySQL do Vipzero.

 

 

 

package br.lb;
 
import java.io.File;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
 
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
 
import com.mysql.jdbc.Connection;
 
public class MySql extends JavaPlugin implements Listener {
 
protected boolean flatfile = true;
 
protected String mysql_url = "";
protected String mysql_user = "";
protected String mysql_pass = "";
protected HashMap<String,String> using_codes = new HashMap<String,String>();
 
 
mysql_url = "jdbc:mysql://"+ getConfig().getString("MySQL.Host").trim()+":"+getConfig().getInt("MySQL.Port")+"/"+getConfig().getString("MySQL.Database").trim()+"";
mysql_user = getConfig().getString("MySQL.Username").trim();
mysql_pass = getConfig().getString("MySQL.Password").trim();
try {
Connection con = DriverManager.getConnection(mysql_url,mysql_user,mysql_pass);
flatfile = false;
if (con == null) {
getLogger().info("Connection to MySQL failed! Changing to flatfile.");
flatfile = true;
 
}
 
else {
getLogger().info("Connected to MySQL server!");
Statement st = con.createStatement();
st.execute("CREATE TABLE IF NOT EXISTS `keys` (`key` VARCHAR(11) PRIMARY KEY, `grupo` VARCHAR(15), `dias` INT);");
st.execute("CREATE TABLE IF NOT EXISTS `vips` (`nome` VARCHAR(30) PRIMARY KEY, `inicio` VARCHAR(11), `usando` VARCHAR(15));");
for(String gname : getConfig().getStringList("vip_groups")) {
try {
PreparedStatement pst2 = con.prepareStatement("ALTER TABLE `vips` ADD COLUMN `"+gname.trim()+"` VARCHAR(15) NOT NULL DEFAULT 0;");
pst2.execute();
pst2.close();
}
catch(SQLException e) {}
}
if(getConfig().getBoolean("logging.usekey"))
st.execute("CREATE TABLE IF NOT EXISTS `vipzero_log` (`comando` VARCHAR(20), `nome` VARCHAR(30), `key` VARCHAR(11) PRIMARY KEY, `data` VARCHAR(11), `grupo` VARCHAR(15), `dias` INT);");
st.close();
}
con.close();
}
catch (SQLException e) {
getLogger().warning("Connection to MySQL failed! Changing to flatfile.");
e.printStackTrace();
flatfile=true;
}
}
 
}
}
 
 

 
 
Estou com 2 problemas.. Quero criar um classe MySQL e colocar tudo do MySQL lá e fazer os dados MySQL na config.yml..
O que preciso colocar na main e o que preciso colocar na classe MySQL..? Já vi alguns tutoriais antigos aqui no fórum, porém nada que fizesse eu tirar essa dúvida.
Como posso fazer isso?
Editado por Burpo
Link para o comentário
Compartilhar em outros sites

3 respostass a esta questão

Posts Recomendados

Bora lá então...
Primeiro, coloca essas duas classes onde tu quiser no teu projeto:

 

Database.java

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class Database {

    protected Connection connection;

    protected Database() {
        this.connection = null;
    }

    public abstract Connection openConnection()
            throws SQLException, ClassNotFoundException;

    public boolean checkConnection()
            throws SQLException {
        return (this.connection != null) && (!this.connection.isClosed());
    }

    public Connection getConnection() {
        return this.connection;
    }

    public boolean closeConnection()
            throws SQLException {
        if (this.connection == null) {
            return false;
        }
        this.connection.close();
        return true;
    }

    public ResultSet querySQL(String query)
            throws SQLException, ClassNotFoundException {
        if (!checkConnection()) {
            openConnection();
        }
        Statement statement = this.connection.createStatement();

        ResultSet result = statement.executeQuery(query);

        return result;
    }

    public int updateSQL(String query)
            throws SQLException, ClassNotFoundException {
        if (!checkConnection()) {
            openConnection();
        }
        Statement statement = this.connection.createStatement();

        int result = statement.executeUpdate(query);

        return result;
    }

}

MySQL.java

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

public class MySQL extends Database {

    private final String user;
    private final String database;
    private final String password;
    private final String port;
    private final String hostname;

    public MySQL(String hostname, String port, String username, String password) {
        this(hostname, port, null, username, password);
    }

    public MySQL(String hostname, String port, String database, String username, String password) {
        this.hostname = hostname;
        this.port = port;
        this.database = database;
        this.user = username;
        this.password = password;
    }

    @Override
    public Connection openConnection()
            throws SQLException, ClassNotFoundException {
        if (checkConnection()) {
            return this.connection;
        }
        String connectionURL = "jdbc:mysql://" + this.hostname + ":" + this.port;
        if (this.database != null) {
            connectionURL = connectionURL + "/" + this.database;
        }
        Class.forName("com.mysql.jdbc.Driver");
        this.connection = DriverManager.getConnection(connectionURL, this.user, this.password);

        return this.connection;
    }
}

Agora, eu recomendo você criar variáveis pras String de configuração do MySQL já na onEnable(), mas você que sabe. Depois disso, só criar um void onde quiser com o seguinte código e chamar ele depois que as Strings de configuração já tiverem um valor atribuído a elas.
 

public static Connection connection;
public static final MySQL mysql = new MySQL(hostname, port, database, username, password); // hostname, port, etc. são as Strings que você pegou da configuração

public static void connect() {
    try {
        connection = mysql.openConnection();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Se não tiver entendido, só chamar DM ou skype (marc0.asm).

Link para o comentário
Compartilhar em outros sites

Bora lá então...

Primeiro, coloca essas duas classes onde tu quiser no teu projeto:

 

Database.java

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class Database {

    protected Connection connection;

    protected Database() {
        this.connection = null;
    }

    public abstract Connection openConnection()
            throws SQLException, ClassNotFoundException;

    public boolean checkConnection()
            throws SQLException {
        return (this.connection != null) && (!this.connection.isClosed());
    }

    public Connection getConnection() {
        return this.connection;
    }

    public boolean closeConnection()
            throws SQLException {
        if (this.connection == null) {
            return false;
        }
        this.connection.close();
        return true;
    }

    public ResultSet querySQL(String query)
            throws SQLException, ClassNotFoundException {
        if (!checkConnection()) {
            openConnection();
        }
        Statement statement = this.connection.createStatement();

        ResultSet result = statement.executeQuery(query);

        return result;
    }

    public int updateSQL(String query)
            throws SQLException, ClassNotFoundException {
        if (!checkConnection()) {
            openConnection();
        }
        Statement statement = this.connection.createStatement();

        int result = statement.executeUpdate(query);

        return result;
    }

}
MySQL.java

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

public class MySQL extends Database {

    private final String user;
    private final String database;
    private final String password;
    private final String port;
    private final String hostname;

    public MySQL(String hostname, String port, String username, String password) {
        this(hostname, port, null, username, password);
    }

    public MySQL(String hostname, String port, String database, String username, String password) {
        this.hostname = hostname;
        this.port = port;
        this.database = database;
        this.user = username;
        this.password = password;
    }

    @Override
    public Connection openConnection()
            throws SQLException, ClassNotFoundException {
        if (checkConnection()) {
            return this.connection;
        }
        String connectionURL = "jdbc:mysql://" + this.hostname + ":" + this.port;
        if (this.database != null) {
            connectionURL = connectionURL + "/" + this.database;
        }
        Class.forName("com.mysql.jdbc.Driver");
        this.connection = DriverManager.getConnection(connectionURL, this.user, this.password);

        return this.connection;
    }
}
Agora, eu recomendo você criar variáveis pras String de configuração do MySQL já na onEnable(), mas você que sabe. Depois disso, só criar um void onde quiser com o seguinte código e chamar ele depois que as Strings de configuração já tiverem um valor atribuído a elas.

 

public static Connection connection;
public static final MySQL mysql = new MySQL(hostname, port, database, username, password); // hostname, port, etc. são as Strings que você pegou da configuração

public static void connect() {
    try {
        connection = mysql.openConnection();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Se não tiver entendido, só chamar DM ou skype (marc0.asm).

 

Mandei solicitação.

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.
×
×
  • Criar Novo...