简体   繁体   中英

Executing JDBC MySQL query with this custom method

I've been doing my homework and I decided to re-write my vote4cash class which manages the mysql for my vote4cash reward system into a new class called MysqlManager. The MysqlManager class I've made needs to allow the Commands class to connect to mysql - done and it needs to allow the Commands class to execute a query - I need help with this part. I've had a lot more progress with the new class that I've made but I'm stuck on one of the last, most important parts of the class, again, allowing the commands class to execute a query.

In my MysqlManager class I have put the code to connects to MySql under

public synchronized static void createConnection() {

Now I just need to put the code that allows the Commands class to execute a query under this as well. I've researched and tried to do this for a while now, but I've had absolutely no luck.

The entire MysqlManager class:

package server.util;

/*
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
*/
import java.sql.*;
import java.net.*;
import server.model.players.Client;//Will be needed eventually so that I can reward players who have voted.

/**
 * MySQL and Vote4Cash Manager
 * @author Cloudnine
 *
 */

public class MysqlManager {

    /** MySQL Connection */
    public static Connection conn = null;
    public static Statement statement = null;
    public static ResultSet results = null;
    public static Statement stmt = null;
    public static ResultSet auth = null;
    public static ResultSet given = null;

    /** MySQL Database Info */
    public static String DB = "vote4gold";
    public static String URL = "localhost";
    public static String USER = "root";
    public static String PASS = "";
    public static String driver = "com.mysql.jdbc.Driver"; //Driver for JBDC(Java and MySQL connector)

    /** Connects to MySQL Database*/
    public synchronized static void createConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(URL + DB, USER, PASS);
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            Misc.println("Connected to MySQL Database");
        } 
        catch(Exception e) {            
            //e.printStackTrace();
        }
    }

    public synchronized static void destroyConnection() {
        try {
            statement.close();
            conn.close();
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    public synchronized static ResultSet query(String s) throws SQLException {
        try {
            if (s.toLowerCase().startsWith("select")) {
                ResultSet rs = statement.executeQuery(s);
                return rs;
            } else {
                statement.executeUpdate(s);
            }
            return null;
        } catch (Exception e) {
            destroyConnection();
            createConnection();
            //e.printStackTrace();
        }
        return null;
    }
}

The snippet of my command:

if (playerCommand.equals("claimreward")) {
                try {
                    PreparedStatement ps = DriverManager.getConnection().createStatement("SELECT * FROM votes WHERE ip = hello AND given = '1' LIMIT 1");
                    //ps.setString(1, c.playerName);
                    ResultSet results = ps.executeQuery();
                    if(results.next()) {
                        c.sendMessage("You have already been given your voting reward.");
                    } else {
                        ps.close();
                        ps = DriverManager.getConnection().createStatement("SELECT * FROM votes WHERE ip = hello AND given = '0' LIMIT 1");
                        //ps.setString(1, playerCommand.substring(5));
                        results = ps.executeQuery();
                        if(results.next()) {
                            ps.close();
                            ps = DriverManager.getConnection().createStatement("UPDATE votes SET given = '1' WHERE ip = hello");
                            //ps.setString(1, playerCommand.substring(5));
                            ps.executeUpdate();
                            c.getItems().addItem(995, 5000000); 
                            c.sendMessage("Thank you for voting! You've recieved 5m gold!");
                        } else {
                            c.sendMessage("You haven't voted yet. Vote for 5m gold!");
                        }
                    }
                    ps.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return;

How the command works: When a player types ::commandname(in this case, claimreward), the commands function will be executed. This isn't the entire commands class, just the part that I feel is needed to be posted for my question to be detailed enough for a helpful answer.

Note: I have all my imports.

Note: Mysql connects successfully.

Note: I need to make the above command code snippet able to execute mysql queries.

Note: I prefer the query to be executed straight from the command, instead of from the MysqlManager, but I will do whatever I need to resolve this problem.

I feel that I've described my problem detailed and relevantly enough, but if you need additional information or understanding on anything, tell me and I'll try to be more specific.


Thank you for taking the time to examine my problem. Thanks in advance if you are able to help. -Alex

Your approach is misguided on many different levels, I can't even start to realize what should be done how here.

1) Don't ever use static class variables unless you know what you do there (and I'm certain, you don't)

2) I assume there is a reason you create your own jdbc connection (eG its part of your homework) if not, you shouldn't do that. I see you use DriverManager and PreparedStatement in one part, you should continue to use them.

3) Your approach seems to intend to start with a relative good code base (your command part) and then goes to a very low-level crude approach on database connections (your MysqlManager ) unless really necessary and you know what you do, you should stay on the same level of abstraction and aim for the most abstract that fits your needs. (In this case, write MysqlManager the way you wrote Command )

4) In your previous question (that you just assumed everybody here has read, which is not the case) you got the suggestion to redesign your ideas, you should do that. Really, take a class in coding principles learn about anti-patterns and then start from scratch.

So in conclusion: Write at least the MysqlManager again, its fatally broken beyond repair. I'm sorry. Write me an email if you have further questions, I will take my time to see how I can help you. (an@steamnet.de)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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