简体   繁体   English

MySQL - Java - BukkitAPI - 连接MySQL数据库时出错

[英]MySQL - Java - BukkitAPI - Error while connecting to MySQL database

I'm trying to make a Bukkit plugin with MySQL support. 我正在尝试制作一个支持MySQL的Bukkit插件。 The plugin that I'm making is a eco plugin, so I have to put all the names of the players in a MySQL table. 我正在制作的插件是一个eco插件,因此我必须将所有播放器的名称放在MySQL表中。 I'm using a PlayerJoinEvent to register the player in the database if they haven't been registered yet. 如果尚未注册,我正在使用PlayerJoinEvent在数据库中注册该播放器。 When I enable my plugin it isn't giving any errors, but when a player joins(that is when the PlayerJoinEvent gets fired) an error appears. 当我启用我的插件时,它没有给出任何错误,但是当玩家加入时(即当PlayerJoinEvent被触发时)会出现错误。

[19:07:54 INFO]: UUID of player behhhans is da772a82-cdc9-3b79-962b-4cdc7623dd7a

[19:07:54 ERROR]: Could not pass event PlayerLoginEvent to Tokeconomy v1.0
org.bukkit.event.EventException
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:294) ~[spigot.jar:git-Spigot-1523]
        at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.jav
a:62) ~[spigot.jar:git-Spigot-1523]
        at org.bukkit.plugin.TimedRegisteredListener.callEvent(TimedRegisteredLi
stener.java:30) ~[spigot.jar:git-Spigot-1523]
        at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.j
ava:502) [spigot.jar:git-Spigot-1523]
        at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.j
ava:487) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.PlayerList.attemptLogin(PlayerList.java:
400) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.LoginListener.c(LoginListener.java:97) [
spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.LoginListener.a(LoginListener.java:43) [
spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.NetworkManager.a(NetworkManager.java:187
) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.ServerConnection.c(ServerConnection.java
:81) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.MinecraftServer.v(MinecraftServer.java:7
20) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.DedicatedServer.v(DedicatedServer.java:2
83) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.MinecraftServer.u(MinecraftServer.java:5
83) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.MinecraftServer.run(MinecraftServer.java
:489) [spigot.jar:git-Spigot-1523]
        at net.minecraft.server.v1_7_R3.ThreadServerApplication.run(SourceFile:6
28) [spigot.jar:git-Spigot-1523]
Caused by: java.lang.NullPointerException
        at me.bramhaag.Tokeconomy.MySQLHandler.createAccount(MySQLHandler.java:1
02) ~[?:?]
        at me.bramhaag.Tokeconomy.EventListener.onLogin(EventListener.java:27) ~
[?:?]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0
_65]
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.7.0
_65]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1
.7.0_65]
        at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.7.0_65]
        at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:292) ~[spigot.jar:git-Spigot-1523]
        ... 14 more
[19:07:54 INFO]: behhhans[/127.0.0.1:57702] logged in with entity id 6067 at ([w
orld] 710.6999999880791, 41.0, 309.4669731960532)

MySQLHandler class: MySQLHandler类:

package me.bramhaag.Tokeconomy;

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 MySQLHandler {

    private Main plugin;

    public MySQLHandler (Main plugin)
    {
        this.plugin = plugin;
    }


    Connection conn = null;

    private String host, port, user, password, database;

    public MySQLHandler(String host, String port, String database, String user, String password) {
        this.host = host; this.port = port; this.user = user; this.password = password; this.database = database;
    }

    public void connect() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password);

            conn.createStatement().execute("CREATE TABLE IF NOT EXISTS `tokens` (`Name` varchar(32), `amount` int)");
        } catch (ClassNotFoundException e) { e.printStackTrace();
        } catch (SQLException e) { e.printStackTrace(); }
    }


    public void createAccount(String player) throws SQLException {


           try (PreparedStatement pstat = conn.prepareStatement("SELECT 1 FROM tokens WHERE name=? LIMIT 1"))// Error line (Line 102)!
           {
               pstat.setString(1, player);

               try (ResultSet rs = pstat.executeQuery()) 
               {
                   if (!rs.next()) 
                   {
                       pstat.executeUpdate("UPDATE `tokens` (`Name`,`amount`) VALUE ('" + player + "', '" + 0 + "')");
                   }
               }
           }
    }

    public void updateLast(String player) {
        try {
            conn.createStatement().execute("UPDATE `bsp` SET `lastlogin` = '"+ String.valueOf(System.currentTimeMillis()) +"'");
        } catch (SQLException e) { e.printStackTrace(); }
    }

    public int getTokens(String pname) throws SQLException {

        ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM `tokens` WHERE `Name`='"+ pname + "';");
        if(!rs.next()) {
            return 0;
        }
        return rs.getInt("amount");
    }

    public void updatePlayerAdd(String pname, double amount) throws SQLException {

        int tokens = this.getTokens(pname);
        if(tokens!=0) {
            conn.createStatement().executeUpdate("UPDATE `tokens` SET `amount`='"+ (tokens + amount)+"' WHERE `Name`='"+ pname + "';");
        } else {
            conn.createStatement().executeUpdate("INSERT INTO `tokens` (`Name`, `amount`) VALUES('" + pname +",'1');");
        }
    }

    public void updatePlayerReject(String pname, double amount) throws SQLException {

        int tokens = this.getTokens(pname);
        if(tokens!=0) {
            conn.createStatement().executeUpdate("UPDATE `tokens` SET `amount`='"+ (tokens - amount)+"' WHERE `Name`='"+ pname + "';");
        } else {
            conn.createStatement().executeUpdate("INSRT INTO `tokens` (`Name`, `amount`) VALUES('" + pname +",'1');");
        }
    }

    public void updatePlayerSet(String pname, double amount) throws SQLException {

        int tokens = this.getTokens(pname);
        if(tokens!=0) {
            conn.createStatement().executeUpdate("UPDATE `tokens` SET `amount`='"+ (amount)+"' WHERE `Name`='"+ pname + "';");
        } else {
            conn.createStatement().executeUpdate("INSRT INTO `tokens` (`Name`, `amount`) VALUES('" + pname +",'1');");
        }
    }

}

EventHandler class: EventHandler类:

package me.bramhaag.Tokeconomy;

import java.sql.SQLException;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class EventListener implements Listener {

    private Main plugin;

     public EventListener (Main plugin)
     {
      this.plugin = plugin;
     }

     MySQLHandler mysql = new MySQLHandler(plugin);


     @EventHandler
     public void onJoin(PlayerJoinEvent e) throws SQLException {
      Player p = e.getPlayer();
      String name = p.getName();

      mysql.createAccount(name);

     }

}

Could someone maybe look at my code and find the error? 有人可能会查看我的代码并找到错误吗?

Thanks, I really need to know how to fix this 谢谢,我真的需要知道如何解决这个问题

I think it is because you are using a PlayerLoginEvent instead of a PlayerJoinEvent . 我认为这是因为你使用的是PlayerLoginEvent而不是PlayerJoinEvent I am not sure but you can at least try it ;) 我不确定但你至少可以尝试一下;)

The PlayerJoinEvent only triggers when the player successfully connects with the server, but the PlayerLoginEvent is also triggered when for example a banned player tries to connect. PlayerJoinEvent仅在玩家与服务器成功连接时触发,但是当禁用的玩家尝试连接时也会触发PlayerLoginEvent

  1. DONT save the Playername. 不要保存玩家名称。 Save the UUID > MC 1.8 change will allow you to change your Nick. 保存UUID> MC 1.8更改将允许您更改您的Nick。 I'm not going into detail, google it there are 100 examples. 我不打算详细介绍,谷歌有100个例子。

  2. try (PreparedStatement pstat = conn.prepareStatement("SELECT 1 FROM tokens WHERE name=? LIMIT 1"))// Error line (Line 102)! try(PreparedStatement pstat = conn.prepareStatement(“SELECT 1 FROM tokens WHERE name =?LIMIT 1”))//错误行(第102行)!

You're tring to get the Column "1" from the Database. 你想从数据库中获取列“1”。 Are you sure that's the column you need? 你确定这是你需要的专栏吗?

Otherwise it's probably the Connection conn > Try to debug it and print out the Connection/Check if you're connected before you try to create the Statement. 否则,它可能是Connection conn>尝试调试它并在尝试创建Statement之前打印出连接/检查是否已连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM