Search code examples
javamysqljdbcircbots

Java adding extra passed variables


First of all, I should probably mention that I'm pretty new to Java.

I'm using PircBot and JDBC to make an irc bot that returns some MySQL values. The problem I'm having is that I want to make prepared statements to protect from SQL injection. However, because I can't add extra variables into my method, I can't seem to get it to work.

This is my code as of now: http://pastebin.com/K8zCKt9f

Basically, I want to use prepared SQL statements, but I can't pass Connection conn into the onMessage method without it messing up (onMessage does not trigger on IRC). This means that I'd have to create a new connection every time there's an if statement, as opposed to how it works right now with the MySQL method.

I'm sure there's an easier/cleaner way to do this, but I can't seem to figure it out. Any help is appreciated, thanks!


Solution

  • Use a member variable to store the connection, and construct the connection when the Ross-object is constructed:

    public class Ross extends PircBot {
    
        private Connection conn;
    
    
        public Ross() {
    
                this.setName("RICK_ROSS");
                this.setVersion("v1.0");
                this.setLogin("not_a_bot");
                if (!main.password.equals("")) this.sendMessage(main.loginbot, "auth "+main.username+" "+main.password);
    
                //Set up MySQL-connection
                Connection conn = null;
                String url = "jdbc:mysql://";
                Class.forName ("com.mysql.jdbc.Driver");
                conn = DriverManager.getConnection (url,"","");
        }
        ...The rest...
    

    Now you can use the member variable conn in other methods of the class.