简体   繁体   English

使用此自定义方法执行JDBC MySQL查询

[英]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. 我一直在做作业,因此决定将我的钢笔投票系统重写为一个名为MysqlManager的新类,它管理我的钢笔投票系统的mysql。 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. 我创建的MysqlManager类需要允许Commands类连接到mysql-完成了,它需要允许Commands类执行查询-我需要这部分的帮助。 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 在我的MysqlManager类中,我将代码连接到

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. 现在,我只需要放置允许Commands类在此条件下执行查询的代码。 I've researched and tried to do this for a while now, but I've had absolutely no luck. 我已经研究并尝试了一段时间,但是我绝对没有运气。

The entire MysqlManager class: 整个MysqlManager类:

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. 命令的工作方式:当玩家键入:: commandname(在这种情况下为Claimreward)时,将执行command函数。 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. 注意:Mysql成功连接。

Note: I need to make the above command code snippet able to execute mysql queries. 注意:我需要使上面的命令代码片段能够执行mysql查询。

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. 注意:我更喜欢直接从命令而不是从MysqlManager执行查询,但是我将尽我所能解决此问题。

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) 1)永远不要使用static类变量,除非您知道在那里做什么(而且我敢肯定,您不会)

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. 2)我认为有一个原因创建您自己的jdbc连接(例如,它是家庭作业的一部分),否则,您不应该这样做。 I see you use DriverManager and PreparedStatement in one part, you should continue to use them. 我看到您在一部分中使用了DriverManagerPreparedStatement ,您应该继续使用它们。

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. 3)您的方法似乎打算从一个相对好的代码库(您的command部分)开始,然后转到数据库连接的一个非常低级的粗略方法(您的MysqlManager ),除非确实有必要并且您知道自己要做什么,否则应该保持相同的抽象水平,并针对适合您需求的最抽象。 (In this case, write MysqlManager the way you wrote Command ) (在这种情况下,写MysqlManager你写的方式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. 4)在上一个问题(您只是假设这里的每个人都阅读过,不是这样)中,您得到了重新设计想法的建议,您应该这样做。 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. 因此,可以得出结论:至少再次编写MysqlManager,其致命故障无法修复。 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) (an@steamnet.de)

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

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