繁体   English   中英

SQLite - 如何先插入然后更新数据库中的行?

[英]SQLite - How to first insert then update rows inside the database?

问题:将值插入数据库然后更新值的最佳方法是什么?

我对 SQLite 比较陌生,但是我在更改数据库中一行的值时遇到了麻烦。 我在下面复制并粘贴了整个 class:

public class Database {

    private final GalaxyCore plugin;
    private Connection connection;

    public Database(GalaxyCore plugin) {
        this.plugin = plugin;
    }

    @Nullable
    public Connection getConnection() {
        File dataFolder = new File(this.plugin.getDataFolder(), "database.db");
        if (!dataFolder.exists()) {
            try {
                if (dataFolder.createNewFile()) {
                    this.plugin.getLogger().info(StringUtil.PREFIX + ChatColor.GREEN + " Successfully created new database folder for storing player information.");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (this.connection != null && !this.connection.isClosed()) {
                return this.connection;
            }

            Class.forName("org.sqlite.JDBC");
            this.connection = DriverManager.getConnection("jdbc:sqlite:" + dataFolder);
            this.connection.setAutoCommit(true);
            return this.connection;
        } catch (ClassNotFoundException | SQLException e) {
            this.plugin.getLogger().log(Level.SEVERE, "Failed to retrieve database connection", e);
        }

        return null;
    }

    public void loadDatabase() {
        this.connection = this.getConnection();
        try {
            if (this.connection != null) {
                Statement createTableStatement = this.connection.createStatement();
                createTableStatement.executeUpdate("CREATE TABLE IF NOT EXISTS userdata ("
                        + "unique_id MESSAGE_TEXT NOT NULL,"
                        + "receive_alerts INTEGER,"
                        + "receive_pings INTEGER,"
                        + "last_spawn_hat MESSAGE_TEXT NOT NULL"
                        + ");");
                createTableStatement.close();
            }
        } catch (SQLException e) {
            this.plugin.getLogger().log(Level.SEVERE, "Failed to load information from database", e);
        }
    }

    @Nullable
    public PlayerData readPlayerData(Player player) {
        UUID playerUUID = player.getUniqueId();
        Connection playerConnection;
        PreparedStatement statement = null;
        ResultSet result = null;
        try {
            playerConnection = this.getConnection();
            if (playerConnection != null) {
                statement = playerConnection.prepareStatement("SELECT * FROM userdata WHERE unique_id = '" + playerUUID + "';");
                result = statement.executeQuery();
                if (result.getString("unique_id").equals(playerUUID.toString())) {
                    String name = result.getString("username");
                    int alerts = result.getInt("receive_alerts");
                    boolean receiveAlerts = result.getInt("receive_alerts") == 1;
                    boolean receivePings = result.getInt("receive_pings") == 1;
                    Material spawnHat = Material.getMaterial(result.getString("last_spawn_hat"));

                    PlayerData playerData = new PlayerData(player);
                    playerData.setReceiveAlerts(receiveAlerts);
                    playerData.setReceivePings(receivePings);
                    playerData.setLastSpawnHat(new ItemStack(spawnHat == null ? Material.GLASS : spawnHat));
                    return playerData;
                }
            }
        } catch (SQLException e) {
            this.plugin.getLogger().log(Level.SEVERE, "Failed to read player data profile for " + player.getName(), e);
        } finally {
            this.close(statement, result);
        }

        return null;
    }

    public void writePlayerData(PlayerData playerData) {
        UUID playerUUID = playerData.getUniqueID();
        Connection playerConnection;
        PreparedStatement statement;
        try {
            playerConnection = this.getConnection();
            if (playerConnection != null) {
                statement = playerConnection.prepareStatement("INSERT INTO userdata(unique_id, receive_alerts, receive_pings, last_spawn_hat) VALUES(?, ?, ?, ?)");
                statement.setString(1, playerUUID.toString());
                statement.setInt(2, playerData.isReceiveAlerts() ? 1 : 0);
                statement.setInt(3, playerData.isReceivePings() ? 1 : 0);
                statement.setString(4, playerData.getLastSpawnHat() == null ? Material.GLASS.toString() : playerData.getLastSpawnHat().getType().toString());
                statement.executeUpdate();
                statement.close();
            }
        } catch (SQLException e) {
            this.plugin.getLogger().log(Level.SEVERE, "Failed to write player data profile for " + playerData.getName(), e);
        }
    }

    public void close(PreparedStatement statement, ResultSet result) {
        try {
            if (statement != null) {
                statement.close();
            }

            if (result != null) {
                result.close();
            }
        } catch (SQLException e) {
            this.plugin.getLogger().log(Level.SEVERE, "Failed to close SQLite connection with database", e);
        }
    }
}

本质上,class 创建了一个数据库,其中存储了一个人的唯一 ID、两个用于接收警报和 ping 的布尔值以及他们选择的最后一个项目的名称(或多或少)。 当我第一次启动我的程序时,数据库会相应地工作。 如果我切换receive_alerts条目,该值将被更新并保存。 但是,如果我再次切换它并尝试保存,它不会覆盖数据库中的原始值。

我相信我的问题是由于插入了值,而不是更新了值。 但是,我不确定如何检查列中是否已存在值。 我试过简单的谷歌搜索,但没有任何重要的东西出现。

我在想我可以先检查一下玩家的unique_id是否已经存在于第 1 列中。如果存在,则UPDATE 如果没有,那么INSERT 但我该怎么做呢?

您可以先运行此命令 -

select count(*) from table_name where id=unique_id;

如果它返回 1,你知道它存在,那么你可以运行更新 SQL 查询。

暂无
暂无

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

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