Alright, so here's a little bit of background:
I am currently trying to develop a referral application. There is a link on our website where a user can refer their friends to our game server (Minecraft). It will input the referrer's information into a database (hosted on my website) and send a link to the "friend". The friend clicks on the link and enters their information (which also gets stored in the database). All of this is working great! (Yay!) So, now for the Java Plugin!
What is supposed to happen...
I have an Event Listener that will fire whenever a user logs into the game. Essentially, it would check the data base for the user's info, and if the user meets the criteria, then it will award them with their extra referral goodies.
What I am trying to do right now...
Right now, I am essentially trying to just get it to connect and display the id of the row, and the ref_id (Referral ID) when the plugin is enabled. But, I'm getting the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
So, without further ado, here is my singular Java document. Of course, that is not the real username and login information to my database. ;) But I'm hoping someone here can tell me what's wrong, because I'm so lost, right now.
package com.arithia.plugins;
import java.sql.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class ArithiaReferrals extends JavaPlugin implements Listener {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://66.147.244.122:3306/graphja6_referrals";
// Database credentials
static final String USER = "fake_username";
static final String PASS = "fake_password";
#Override
public void onEnable() {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// STEP 3: Open a connection
getLogger().info("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
getLogger().info("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, ref_id FROM referred_users";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int ref_id = rs.getInt("ref_id");
// Display values
getLogger().info("ID: " + id);
getLogger().info("Referral ID: " + ref_id);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}finally{
// finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
} // nothing we can do
try {
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
} // End Finally try
} // end try
getLogger().info("Goodbye!");
getLogger().info("The [Arithia Referrals] plugin was enabled!");
}
#Override
public void onDisable() {
getLogger().info("The [Arithia Referrals] plugin was disabled!");
}
#EventHandler
public void onPlayerLogin(PlayerLoginEvent e) {
// "Check database for player..."
}
}
Other Information...
Database Name: graphja6_referrals
Database Table: referred_users
Note: I am not entirely sure that the DB_URL is correct... 66.147.244.122 is the correct IP, but I'm not entirely sure about the port or anything else, so if someone could verify that's correct, I'd be appreciative.
Thank you very much for your help.
Okay, so I'm just an idiot.
For anyone else getting this error, you need to whitelist the IP of the remote connection for this to work. It is a firewall thing, and depending on who you host with, there's probably a "Remote MySQL" option in the cPanel. Add the IP to the remote client that is trying to access the database, so it will be whitelisted.
Thank you to everyone who tried to help. <3
Related
I am working on a hotel management system project and I want to make a login platform, which takes data from an AWS RDS PostgreSQL server that I have created. The problem is that people from other networks who I sent the .exe file of this project can't login but I can.
I have created the tables I wanted in pgAdmin4 and also I have installed the Postgres drivers in my project libraries.
Here is my connection class, where URL, user and pass are defined in the project:
public class ServerConnection {
static Connection getConnection() {
Connection connection = null;
try{
connection = DriverManager.getConnection(url, user, pass);
if(connection != null) {
System.out.println("Connected");
}
else {
System.out.println("Failed");
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
And below is the login method:
public void performLogin() {
PreparedStatement st;
ResultSet rs;
String user = username.getText();
String pass = String.valueOf(password.getPassword());
String query = "SELECT * FROM ADMINS WHERE username=? AND passw=?";
try {
st = serverConnection.getConnection().prepareStatement(query);
st.setString(1, user);
st.setString(2, pass);
rs = st.executeQuery();
if(rs.next()) {
hotelFrame2 hf2 = new hotelFrame2();
this.dispose();
}
else {
JOptionPane.showMessageDialog(null, "Invalid Username / Password","LoginError",2);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
How can I fix it?
The problem is that people from other networks who I sent the .exe
file of this project can't login but I can.
It seems you are authorizing only your computer(IP) to connect to the RDS database, to solve your issue you have to open the flow to the other people by changing the security group.
By the way, using JDBC with AWS really hurt me, it is really an old way, it's better to look at JPA, Hibernate, or even some other AWS services.
I'm trying to write a servlet application for learning purposes that connects to an Oracle database, queries some data and then prints it to the browser. Simple!
However, I'm experiencing an ORA-01017: invalid username/password when attempting to connect to a locally installed and running version of Oracle XE (19c). For the sake of testing the connection, I'm connection with the system user. Here's my code:
// http://localhost:8080/demo/
public class DemoServ extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The user that I'm using absolutely does exist, and I can connect using SQL Developer without issue.
I would be willing to put this down to my own ignorance of Java, but if I run the following code independently of any servlet, I can connect and execute the sample query!
public class DataReader {
public static void main (String [] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT count(*) num FROM dual");
if (rs.next()) {
int i = rs.getInt("num"); // get first column returned
System.out.println("number: " + i);
}
rs.close();
statement.close();
con.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
I've been searching Google for solutions to this, but I have been unable to find a solution, so here I am.
I'm working on Windows 10, using Java 1.8 and Oracle 19c XE.
Any help would be great. Thanks
Okay, I finally go this to work, but I cannot explain why.
Oracle 19c is case sensitive, which I knew. I attempted to disable this, but as it's a depreciated feature, this seemed expeditious. I altered the password for the system user to be "system", and I can connect successfully. "SYSTEM" as a password continues to fail.
What strikes me as odd about this is that I'm sure that I tried to use the "system" (lowercase) password in the past. :(
Anyway, I probably was doing something daft, but at least I'm got over the hump. Phew!
Thank you to everyone!!
I want to populate a JComboBox with a database column (SQLite).
My database connection is setup through a class called DatabaseConnection setup in anther package.
Here is how it looks like
import java.sql.*;
import javax.swing.JOptionPane;
public class DatabaseConnection {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:database.db");
JOptionPane.showMessageDialog(null, "Connection Established");
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
In my JFrame class I am creating following method, which according to a youtube tutorial should work
public void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
}
catch (SQLException e)
{
e.printStackTrace();
}
}
But it displays following errors at "comboAccountName.addItem(rsJCBaccountname.getString(1));"
Multiple markers at this line
- Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be
parameterized
- comboAccountName cannot be resolved
Please help!
I'm not really sure what you're expecting...
statJCBaccountname isn't even in the code example you've provided, but the compiler is saying that the variable is undefined
There is no such method as createStatement in the DatabaseConnection class
You need to resolve these issues before the program will compile. I'd suggest staying away from YouTube tutorials unless you know the author.
Take a look at JDBC Database Access for more details...
I have started trying out some stuff so that I can use mysql database together with Java. First of all I have some questions about it.
I have used mysql a lot with PHP development but never with Java. Can I use the MySQL that MAMP brings or do I have to install it stand alone or something?
and second.. I have created this code with the help of a tutorial but the only output I get is
com.mysql.jdbc.Driver
The code that I have used for this you can find below:
package Databases;
import java.sql.*;
public class MysqlConnect{
/* These variable values are used to setup
the Connection object */
static final String URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASSWORD = "root";
static final String DRIVER = "com.mysql.jdbc.Driver";
public Connection getConnection() throws SQLException {
Connection con = null;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PASSWORD);
}
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
return con;
}
public void getEmployees() {
ResultSet rs = null;
try {
Statement s = getConnection().createStatement();
rs = s.executeQuery("SELECT id, name, job_id, location FROM person");
System.out.format("%3s %-15s %-7s %-7s%n",
"ID", "NAME", "JOB ID",
"LOCATION");
System.out.format("%3s %15s %7s %7s%n",
"---", "---------------",
"-------", "--------");
while(rs.next()) {
long id = rs.getLong("id");
String name = rs.getString("name");
long job = rs.getLong("job_id");
String location = rs.getString("location");
System.out.format("%-3d %-15s %7d %5s%n",
id, name, job, location);
}
}
catch(SQLException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
}
}
It's coming from the following block:
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
That's a pretty poor way of handling exceptions. You're just printing the exception message. You have no clue what's going on. Rather just throw it (which will end up with a nice stacktrace), or print a more descriptive message along alone the exception message, e.g.
catch(ClassNotFoundException e) {
System.out.println("JDBC driver class not found in runtime classpath: " + e.getMessage());
System.exit(-1);
}
How to fix the particular exception is in turn actually a second question (with a pretty obvious answer: just put JAR file containing JDBC driver class in runtime classpath), but ala, you may find this mini-tutorial helpful then: Connect Java to a MySQL database.
Unrelated to the concrete problem, I'm not sure which tutorial you're reading there, but I'd take it with a grain of salt. Apart from poor exception handling, it's also leaking DB resources in getEmployees() method by never closing the result set, statement and connection. This is absolutely not a good practice either. How to do it is also already covered in the aforelinked mini-tutorial. See further also: How often should Connection, Statement and ResultSet be closed in JDBC?
Yes, you need to install MySQL server locally or remotely.
The code will be usable if you also downloaded jdbc Driver jar from MySQL download pages. and you configured your MySQL instance with the proper username and password.
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 (e.G. 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)