[LIB] SQLibrary - Database wrappers for all database engines

Discussion in 'Resources' started by PatPeter, Aug 26, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    PatPeter

    Next version will have support for ALL databases and several query builders.
     
  2. Offline

    Tamfoolery

    Whenever I start my server I get a nullPointerException and I have no idea why!

    The error:
    Code:
    10:35:06 [INFO] [Trouble in Minecraft] Enabling Trouble in Minecraft v0.0.1
    10:35:06 [SEVERE] Error occurred while enabling Trouble in Minecraft v0.0.1 (Is
    it up to date?)
    java.lang.NullPointerException
            at com.tammcd.troubleinminecraft.Main.sqlConnection(Main.java:89)
            at com.tammcd.troubleinminecraft.Main.onEnable(Main.java:28)
            at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
            at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
    .java:365)
            at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
    r.java:381)
            at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:265)
            at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:247
    )
            at net.minecraft.server.MinecraftServer.i(MinecraftServer.java:296)
            at net.minecraft.server.MinecraftServer.d(MinecraftServer.java:275)
            at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:225)
            at net.minecraft.server.DedicatedServer.init(DedicatedServer.java:140)
            at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:378)
            at net.minecraft.server.ThreadServerApplication.run(SourceFile:539)
    And the code in question (based off @Pew446's tutorial):
    Code:
    public SQLite db;
     
    public void sqlConnection() {
            db = new SQLite(plugin.getLogger(), "Trouble in Minecraft", "game", plugin.getDataFolder().getAbsolutePath());
         
            try {
                db.open();
            } catch (Exception e) {
                plugin.getLogger().info(e.getMessage());
                getPluginLoader().disablePlugin(plugin);
            }
        }
    Any help will be greatly appreciated!
     
  3. Offline

    Lolmewn Retired Staff

    Tamfoolery does your getDataFolder() exist? It has to, otherwise it errors. Can't harm to add
    Code:
    this.getDataFolder().mkdir();
    Also, I don't think it's needed to use the absolute path, relative (as it is I think) works fine too.
     
  4. Offline

    Tamfoolery

    Problem solved! Not only did I add
    Code:
    this.getDataFolder().mkdir();
    , but I also changed 'plugin' to say 'this', and now everything works. Thanks!
     
  5. Offline

    steezo

    No matter what I try, I'm always getting an error saying "Please close your previous ResultSet to run the query: insert into users (username) values ('steezo')"

    As you can see in my code below, I AM closing the ResultSet before executing the insert query.

    EDIT: I just found out where the problem was coming from. When I first load my plugin I am checking if the database tables exist by using sqlite.checkTable("tablename")... If I DON'T do this, I don't get the error telling me to close my ResultSet, so does this checkTable method leave a ResultSet open?

    Code:
    @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            Player player = event.getPlayer();
            try {
                ResultSet result = aMod.sqlite.query("select userid from users where username = '" + player.getName() + "'");
                if (result.next()) {
                    // user is already in the users table
                    result.close();
                    aMod.getLogger().info("User " + player.getName() + " is already in the users table");
                } else {
                    // user is not in the users table, add him
                    result.close();
                    aMod.sqlite.query("insert into users (username) values ('" + player.getName() + "')");
                    aMod.getLogger().info("Added user " + player.getName() + " to the users table");
                }
            } catch (SQLException e) {
                aMod.getLogger().info(e.getMessage());
            }
        }
     
  6. Offline

    puyttre

    I don't understand what I should put for the Logger log parameter. Can someone please help?
    PatPeter ?
    Lolmewn ?

    Edit: As in: What should my "Logger" be? Is that referring to the Bukkit logger or...?
     
  7. Offline

    Lolmewn Retired Staff

    Yes, that is the most used one. In your main class, get it by doing this.getLogger();
     
  8. Offline

    puyttre

    Ok thanks. I just wanted to make sure ;)

    Lolmewn
    Hey I'm having problems with this. I'm not sure why it isn't working:

    Code:java
    1. String name = getConfig().getString("db_name");
    2. String ip = getConfig().getString("ip_address");
    3. String user = getConfig().getString("db_user");
    4. String pword = getConfig().getString("db_password");
    5. String port = getConfig().getString("db_port");
    6.  
    7. public void connectToMysql(){
    8. if(pword == null || pword.equals("")){
    9.  
    10. }else{
    11. Logger logger = Bukkit.getLogger();
    12. MySQL sql = new MySQL(logger, "[MineWare] ", ip, port, name, user, pword);
    13. try{
    14. sql.open();
    15. }catch(Exception e){
    16. log(e.getMessage());
    17. log("Error occured while connecting to MySQL");
    18. }
    19. }
    20. }
    21.  

    Code:
    12-09-19 19:14:27 [SEVERE] Could not load 'plugins\MineWare.jar' in folder 'plugins'
    org.bukkit.plugin.InvalidPluginException: java.lang.IllegalArgumentException: File cannot be null
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:153)
        at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:305)
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:230)
        at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:222)
        at org.bukkit.craftbukkit.CraftServer.reload(CraftServer.java:565)
        at org.bukkit.Bukkit.reload(Bukkit.java:183)
        at org.bukkit.command.defaults.ReloadCommand.execute(ReloadCommand.java:21)
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:168)
        at org.bukkit.craftbukkit.CraftServer.dispatchCommand(CraftServer.java:492)
        at org.bukkit.craftbukkit.CraftServer.dispatchServerCommand(CraftServer.java:488)
        at net.minecraft.server.DedicatedServer.ah(DedicatedServer.java:248)
        at net.minecraft.server.DedicatedServer.q(DedicatedServer.java:213)
        at net.minecraft.server.MinecraftServer.p(MinecraftServer.java:476)
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:408)
        at net.minecraft.server.ThreadServerApplication.run(SourceFile:539)
    Caused by: java.lang.IllegalArgumentException: File cannot be null
        at org.apache.commons.lang.Validate.notNull(Validate.java:203)
        at org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(YamlConfiguration.java:170)
        at org.bukkit.plugin.java.JavaPlugin.reloadConfig(JavaPlugin.java:117)
        at org.bukkit.plugin.java.JavaPlugin.getConfig(JavaPlugin.java:111)
        at me.Puyttre.MineWare.<init>(MineWare.java:94)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:149)
        ... 14 more
    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: May 19, 2016
  9. Offline

    Lolmewn Retired Staff

    puyttre Make sure getConfig() exists, do this by doing
    if(!new File(this.getDataFolder(), "config.yml").exists()){
    //create it
    }
     
    puyttre likes this.
  10. Offline

    puyttre

    Thanks for the help but it still doesn't work D:

    Here's my method again
    Code:java
    1. String name = getConfig().getString("db_name");
    2. String ip = getConfig().getString("ip_address");
    3. String user = getConfig().getString("db_user");
    4. String pword = getConfig().getString("db_password");
    5. String port = getConfig().getString("db_port");
    6.  
    7. public void connectToMysql(){
    8. if(!new File(this.getDataFolder(), "config.yml").exists()){
    9. this.saveDefaultConfig();
    10. connectToMysql();
    11. }else if(this.getConfig() != null){
    12. Logger logger = Bukkit.getLogger();
    13. MySQL sql = new MySQL(logger, "[MineWare] ", ip, port, name, user, pword);
    14. try{
    15. sql.open();
    16. }catch(Exception e){
    17. log(e.getMessage());
    18. log("Error occured while connecting to MySQL");
    19. }
    20. }else{
    21. log("Could not connect to MySQL server. Stopping...");
    22. Bukkit.getServer().shutdown();
    23. }
    24. }

    and heres my onEnable method:
    Code:java
    1. @Override
    2. public void onEnable(){
    3. PluginManager pm = Bukkit.getServer().getPluginManager();
    4.  
    5. p.log("[MineWare] MineWare v 1.0 successfully started.");
    6. this.saveDefaultConfig();
    7. connectToMysql(); // <--- Calls the connectToMysql() method
    8. }


    I don't get any errors in NetBeans and I checked all my imports for errors. Should I somehow make threads to make sure the config saves and then calls the method? Here's the error one last time:

    Code:
    2012-09-20 16:58:47 [INFO] Starting minecraft server version 1.3.1
    2012-09-20 16:58:47 [INFO] Loading properties
    2012-09-20 16:58:47 [INFO] Default game type: SURVIVAL
    2012-09-20 16:58:47 [INFO] Generating keypair
    2012-09-20 16:58:47 [INFO] Starting Minecraft server on *:25564
    2012-09-20 16:58:47 [INFO] This server is running CraftBukkit version git-Bukkit-1.3.1-R1.0-b2320jnks (MC: 1.3.1) (Implementing API version 1.3.1-R1.0)
    2012-09-20 16:58:47 [SEVERE] Could not load 'plugins\MineWare.jar' in folder 'plugins'
    org.bukkit.plugin.InvalidPluginException: java.lang.IllegalArgumentException: File cannot be null
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:153)
        at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:305)
        at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:230)
        at org.bukkit.craftbukkit.CraftServer.loadPlugins(CraftServer.java:222)
        at org.bukkit.craftbukkit.CraftServer.<init>(CraftServer.java:198)
        at net.minecraft.server.ServerConfigurationManagerAbstract.<init>(ServerConfigurationManagerAbstract.java:50)
        at net.minecraft.server.ServerConfigurationManager.<init>(SourceFile:11)
        at net.minecraft.server.DedicatedServer.init(DedicatedServer.java:105)
        at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:380)
        at net.minecraft.server.ThreadServerApplication.run(SourceFile:539)
    Caused by: java.lang.IllegalArgumentException: File cannot be null
        at org.apache.commons.lang.Validate.notNull(Validate.java:203)
        at org.bukkit.configuration.file.YamlConfiguration.loadConfiguration(YamlConfiguration.java:170)
        at org.bukkit.plugin.java.JavaPlugin.reloadConfig(JavaPlugin.java:117)
        at org.bukkit.plugin.java.JavaPlugin.getConfig(JavaPlugin.java:111)
        at me.Puyttre.MineWare.<init>(MineWare.java:98)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:149)
        ... 9 more
    2012-09-20 16:58:47 [INFO] Preparing level "world"
    2012-09-20 16:58:47 [INFO] Preparing start region for level 0 (Seed: 1971544476366856911)
    2012-09-20 16:58:48 [WARNING] ----- Bukkit Auto Updater -----
    2012-09-20 16:58:48 [WARNING] Your version of CraftBukkit is out of date. Version 1.3.1-R2.0 (build #2340) was released on Sun Aug 19 12:52:49 CDT 2012.
    2012-09-20 16:58:48 [WARNING] Details: http://dl.bukkit.org/downloads/craftbukkit/view/01371_1.3.1-R2.0/
    2012-09-20 16:58:48 [WARNING] Download: http://dl.bukkit.org/downloads/craftbukkit/get/01371_1.3.1-R2.0/craftbukkit.jar
    2012-09-20 16:58:48 [WARNING] ----- ------------------- -----
    2012-09-20 16:58:48 [INFO] Preparing start region for level 1 (Seed: 1971544476366856911)
    2012-09-20 16:58:48 [INFO] Preparing start region for level 2 (Seed: 1971544476366856911)
    2012-09-20 16:58:48 [INFO] Preparing spawn area: 28%
    2012-09-20 16:58:48 [INFO] Server permissions file permissions.yml is empty, ignoring it
    2012-09-20 16:58:48 [INFO] Done (1.264s)! For help, type "help" or "?"
    
     
  11. Offline

    PatPeter

    puyttre

    Code:
    // Don't initialize variables that you only use once
    //String name = getConfig().getString("db_name");
    //String ip = getConfig().getString("ip_address");
    //String user = getConfig().getString("db_user");
    //String pword = getConfig().getString("db_password");
    //String port = getConfig().getString("db_port");
    public static Logger log = Logger.getLogger("Minecraft");
    public static FileConfiguration config; // You need to create a Configuration class in your project that extends FileConfiguration
    public static PluginManager pm;
    public static Database sql; // Always save to the abstract class/interface
     
    @Override
    public void onEnable(){
        this.pm = Bukkit.getServer().getPluginManager();
     
        config = getConfig();
        config.options().copyDefaults(true); // This is the line you were missing
        this.saveDefaultConfig();
     
        // CraftBukkit copies it above
        /*if (!new File(this.getDataFolder(), "config.yml").exists()) {
            this.saveDefaultConfig();
            connectToMysql();
        } else if (config != null) {*/
            //this.logger = Bukkit.getLogger();
            this.sql = new MySQL(logger, "[MineWare] ",
                config.getString("db.ip"),
                config.getString("db.port"),
                config.getString("db.name"),
                config.getString("db.user"),
                config.getString("db.password"));
            try{
                sql.open();
            } catch(SQLException e) {
                log(e.getMessage());
                log("Error occured while connecting to MySQL");
            }
        /*} else {
            log("Could not connect to MySQL server. Stopping...");
            Bukkit.getServer().shutdown();
        }*/ // No one wants to use a plugin that shuts down the server if it fails to launch
        //connectToMysql(); // <--- Calls the connectToMysql() method
        p.log("[MineWare] MineWare v 1.0 successfully started."); // Don't say it's successfully started unless it's successfully started
    }
     
    /*public void connectToMysql(){
    }*/
    You should change your config as so:
    Code:
    db:
        ip:
        port:
        name:
        user:
        password:
     
    puyttre likes this.
  12. Offline

    Lolmewn Retired Staff

    Or use saveResource("config.yml"). Note, this requires you to have a config.yml file in your .jar, in the same folder as your plugin.yml.
     
  13. Offline

    puyttre

    Thanks so much! I'm still catching on to Java but this will help a ton.
    Also, thanks so much for the Library!
     
  14. Offline

    PatPeter

    Right, forgot to mention that.

    Thank you for using it :D
     
  15. Offline

    steezo

    Anyone know why I'm getting this error message when trying to check mysql tables?

    [SEVERE] [aMod] [aMod][MySQL] Could not check if table "users" exists, SQLException: Table 'amod.users' doesn't exist

    How could it not check if the table exists and the error message is that it knows the table doesn't exist?
     
  16. Offline

    Lolmewn Retired Staff

    Does the database exist?
     
  17. Offline

    steezo

    Yes the database exists. What's weird is the checkTable method must be returning false because it DOES create the table. If I shut down the server and run it again without changing anything it doesn't try to create the table again either, so it must be able to tell that it exists that time.

    Code:
    if (!mysql.checkTable("users")) {
        mysql.query("create table users blah blah blah");
    }
     
  18. Offline

    Lolmewn Retired Staff

    You could instead use this every time it starts:
    Code:
    mysql.query("CREATE TABLE IF NOT EXISTS users blahblahblah");
     
  19. Offline

    Raemis

    Hello,
    I'm using SQLite, and I'm getting
    Code:
    22:13:55 [WARNING] [MultiHomes] MultiHomes[SQLite] Please close your previous ResultSet to run the query: ... 
    But it only happens once I reboot the server. If its the first time starting the server, and my DB is created fresh, it works fine. If I reboot, I start getting these from all of my queries. Any ideas, or if not, what can I upload to help find the issue?
     
  20. Offline

    bob7

    I like the idea, but i truly do not see any plus sides to this.. Why not use regular SQlite..? What makes this better? This is why you should explain the topic rather then simply posting links. I'm sure a lot of people here are new to sqlite and are very unsure of how it works. You should make a small tutorial, and post your API so that all these developers could better understand, and work with less questions. It's a simple suggestion :)
     
  21. Offline

    Sil3nt_One

    Note to author and all using sqlite database.

    If you get an error with message Please close your previous ResultSet to run the query.
    Its because the tables result set was not closed..
    My plugin worked correctly when the database did not exist at start. But after restarting the craftbukkit server all queries returned the above mentioned error.

    /lib/PatPeter/SQLibrary/SQLite.java
    Find code

    public boolean checkTable(String table) {
    DatabaseMetaData md = null;
    try {
    //dbm = this.open().getMetaData();
    md = this.connection.getMetaData();
    ResultSet tables = md.getTables(null, null, table, null);
    if (tables.next())
    return true;
    else
    return false;
    } catch (SQLException e) {
    this.writeError("Could not check if table \"" + table + "\" exists, SQLException: " + e.getMessage(), true);
    return false;
    }
    }

    Replace it with

    public boolean checkTable(String table) {
    DatabaseMetaData md = null;
    try {
    //dbm = this.open().getMetaData();
    md = this.connection.getMetaData();
    ResultSet tables = md.getTables(null, null, table, null);
    if (tables.next()) {
    tables.close();
    return true;
    }
    else
    return false;
    } catch (SQLException e) {
    this.writeError("Could not check if table \"" + table + "\" exists, SQLException: " + e.getMessage(), true);
    return false;
    }
    }
     
  22. Offline

    Solivero

    I got the exact same problem. I can see you fixed it, there for i would love to see your code for the whole sqlConnection() so i can try it with my plugin.
     
  23. Offline

    Solivero

    Okay, i tried this (and some other versions) but now it gives me a NullPointerExeption at checkTable when having this
    Code:
    public class bukkitPlugin extends JavaPlugin {
        public final Logger logger = Logger.getLogger("Minecraft");
        public static bukkitPlugin plugin;
        public static SQLite sqlite;
       
        @Override
        public void onDisable() {
            PluginDescriptionFile pdfFile = this.getDescription();
            this.logger.info(pdfFile.getName() + " Has Been Disabled!");
            sqlite.close();
        }
       
        @Override
        public void onEnable() {
            PluginDescriptionFile pdfFile = this.getDescription();
            this.logger.info("[" + pdfFile.getName() + "]" + " Version " + pdfFile.getVersion() + " Has Been Enabled!");
            sqlite = new SQLite(logger, "Apartments", "Apartments_table", "plugins/Apartments");
            if(!sqlite.checkTable("Apartments_table")) {
                sqlite.createTable("CREATE TABLE IF NOT EXISTS Apartments_table (id INTEGER PRIAMY KEY AUTOINCREMENT, userText TEXT");
            }
        }
    This is the error i get when starting the server
    Code:
    java.lang.NullPointerException
            at lib.PatPeter.SQLibrary.SQLite.checkTable(SQLite.java:199)
            at com.hotmail.oliven_666.bukkitPlugin.bukkitPlugin.onEnable(bukkitPlugi
    n.java:30)
            at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
            at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader
    .java:374)
            at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManage
    r.java:381)
            at org.bukkit.craftbukkit.CraftServer.loadPlugin(CraftServer.java:272)
            at org.bukkit.craftbukkit.CraftServer.enablePlugins(CraftServer.java:254
    )
            at net.minecraft.server.MinecraftServer.j(MinecraftServer.java:320)
            at net.minecraft.server.MinecraftServer.e(MinecraftServer.java:299)
            at net.minecraft.server.MinecraftServer.a(MinecraftServer.java:258)
            at net.minecraft.server.DedicatedServer.init(DedicatedServer.java:141)
            at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:400)
            at net.minecraft.server.ThreadServerApplication.run(SourceFile:818)
    Does anyone have a clue why i get these NullPointerExeptions all the time? Have tried lots of different ways to code it but all gives me a NullPointerExeption at some place...
     
  24. Offline

    findus1994

    Hey,
    by using the Plugin i also got this error:

    after adding the rs.close() command, the Server showed the following errorcode.


    My Code:

    Code:
    public void checkmaindatabase(){
    if (!database.checkTable("datas")) {
    database.createTable("CREATE TABLE IF NOT EXISTS datas (id INTEGER PRIMARY KEY AUTOINCREMENT, playername varchar(50), vorname varchar(50), nachname varchar(50), lastlogin TIMESTAMP)");
    if (database.checkTable("datas")) {
    log.info("Table created");
    }
    } else if (database.checkTable("datas")) {
    log.info("Maindatabase found");
    } else {
    log.warning("FEHLER: NO TABLE FOUND AND CAN NOT CREATED");
    }
    }
     
    public void insertrowmaintable(String playername) throws SQLException{
    String s1 = "INSERT INTO datas (id, playername, vorname, nachname, lastlogin) VALUES (NULL, 'juhu', 'tada', 'tada', CURRENT_TIMESTAMP);";
    ResultSet rs = database.query(s1);
    rs.close();
    }
    
    Solivero
    I don't know if this is the problem of the NullPointerException, but i think you have a typing error:


    sqlite.createTable("CREATE TABLE IF NOT EXISTS Apartments_table (id INTEGER PRIAMY KEY AUTOINCREMENT, userText TEXT");
     
  25. Offline

    Solivero

    Awesome!!! been having that problem and seen many others having the same problem but no fixes. This fixed it! Thank you very much!
     
    Sil3nt_One likes this.
  26. Offline

    Sil3nt_One

    Welcome.
    It gives no problems in case of MySQL but throws errors if the ResultSet is not closed in case of sqlite.
     
  27. Offline

    PatPeter

    Thank you for finding a logic error. It seems executeQuery() throws an exception if the table isn't found. I'll remove the exception message.

    Yes, after the exception is logged it returns false because it assumes the exception means that the table was not found. As I said above, I'm removing the notification.

    checkTable() and createTable() will be deprecated as of next version. They will be removed somewhere around version 5.

    You have a ResultSet that you forgot to close somewhere in your code.

    What do you mean by the boldened text? And the API is public; the whole library is public.

    I'll make a tutorial when the library is actually finished and has support for every database engine (it almost does, every class is working in my current build except for the query commands).

    Use the CODE BBC tags whenever you need to post code on the forums.

    I've already fixed this in my local repository:

    Code:
    @Deprecated
        @Override
        public boolean checkTable(String table) {
            DatabaseMetaData md = null;
            try {
                md = this.connection.getMetaData();
                ResultSet tables = md.getTables(null, null, table, null);
                if (tables.next()) {
                    tables.close();
                    return true;
                } else {
                    tables.close();
                    return false;
                }
            } catch (SQLException e) {
                this.writeError("Could not check if table \"" + table + "\" exists, SQLException: " + e.getMessage(), true);
                return false;
            }
        }
    I now feel the necessity of committing my changes to GitHub ASAP, as they are thoroughly out-of-date. With the holidays I have some free time so I'll try to do that this weekend.

    I'd love to be able to have the library check this for you, but this is a problem that resides outside my purview. The key is not to get something without checking whether the result is null:

    Code:
    folder = this.getDataFolder();
    if (folder != null)
        continue();
    Thank you for finding a logic error from the first version:

    Code:
    if (query.equals("") || query == null) {
    Always check for null first, to all you coders out there. The check for null is redundant in this example because if it isn't null, the first check will succeed and thus the second check will obviously succeed. If it is null it will throw an exception:

    Code:
    if (query == null || query.equals("")) {
    This is a short-circuit check. If the first check fails it will skip the second check, so that the second check can never throw a NullPointerException.

    query() returns null when you use INSERT, UPDATE, DELETE, etc. Do not save the return of an INSERT, UPDATE, or DELETE query to a ResultSet.

    I apologize for not having committed this update yet.

    Yes, the algorithms are completely different.
     
    puyttre likes this.
  28. Offline

    Bubelbub

    Whats wrong with this?

    Code:
            try {
                ResultSet result = this.connection.query("UPDATE events SET status = '" + newStatus + "' WHERE eventID = '" + eventID + "' AND userID = (SELECT id FROM authme WHERE username = '" + p.getName().toLowerCase() + "');");
                if(result.rowUpdated())
                {
                    result.close();
                    try {
                        result = this.connection.query("REPLACE INTO events SET status = '" + newStatus + "', eventID = '" + eventID + "', userID = (SELECT id FROM authme WHERE username = '" + p.getName().toLowerCase() + "');");
                        result.close();
                    } catch (SQLException e) {
                        System.out.println("[SignEvent] User Fehler: " + e.getMessage());
                    }
                }
                result.close();
            } catch (SQLException exception) {
                System.out.println("[SignEvent] User Fehler: " + exception.getMessage());
            }
     
  29. Offline

    Lolmewn Retired Staff

  30. Offline

    Bubelbub

    No Error.

    It doesnt work.
    I think the "if(result.rowUpdated)" wasnt called.


    I need a example for the php "mysql_affected_rows" function.

    In the code above, i update the rows...
    If there is no row, then he should insert into it.
    In the example, the if sentence must be negative... (first fail)

    A simple "SQLibrary" total example page.
    All functions with descriptions etc.
    I mean, i'm a Developer (incl. MySQL, etc.) but the Extension/Plugin has no Wiki...


    A few examples would make me happy :)


    //edit:
    Ah okay...
    Google about prepare...

    Solution:
    Code:
            try {
                PreparedStatement preSta = this.connection.prepare("UPDATE events SET status = '" + newStatus + "' WHERE eventID = '" + eventID + "' AND userID = (SELECT id FROM authme WHERE username = '" + p.getName().toLowerCase() + "');");
                if(preSta.executeUpdate() < 1)
                {
                    try {
                        this.connection.query("REPLACE INTO events SET status = '" + newStatus + "', eventID = '" + eventID + "', userID = (SELECT id FROM authme WHERE username = '" + p.getName().toLowerCase() + "');").close();
                    } catch (SQLException e) {
                        System.out.println("[SignEvent] User Fehler: " + e.getMessage());
                    }
                }
            } catch (SQLException exception) {
                System.out.println("[SignEvent] User Fehler: " + exception.getMessage());
            }
     
Thread Status:
Not open for further replies.

Share This Page