Follow up question from here
Here is my current code, I try to preform the check to see if they have any tokens and then set the tokens if they dont but it seems to just be running the code no matter if I set it or not.
#EventHandler
public void onJoin(PlayerJoinEvent event) throws SQLException {
Player player = event.getPlayer();
String name = player.getName();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
res.next();
int tokens = 0;
if (res.getString("PlayerName") == null) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}
player.sendMessage(tokens + " Tokens.");
}
The way you check for a row's existence is wrong. Take a look at your query:
"SELECT * FROM tokens WHERE PlayerName = '" + name + "'
If a player does not exist in the table, this query will return 0 rows, not a row with null for the player's name, like you're checking now. Instead, you should check if the ResultSet has a row:
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
int tokens = 0;
if (res.next()) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}
Related
I've been trying to solve this issue for the past couple of days. I have a SerachUser function where I input all the data like age, gender, city and interests into each string and check them into a select query command.
If data is present, I print them out.
Unfortunately the search isn't working completely. For eg: my table user doesn't have 'F' gender. But if I type 'F' I still get data instead of displaying "ResultSet in empty in Java".
Below is a brief code I have done.
try{
conn = DriverManager.getConnection(DB_URL,"shankarv5815","1807985");
st = conn.createStatement();
rs = st.executeQuery("Select loginID, f_name, l_name from users where gender = '" +
searchUser.getGender() + "' and age between '" + min + "' and '" + max + "' and city = '" +
searchUser.getCity() + "' and interest1 = '" + searchUser.getInterest1() +
"' or interest2 = '" + searchUser.getInterest1() + "' or interest3 = '" +
searchUser.getInterest1() + "' and loginID != '" + curUser + "'");
if (rs.next() == false) {
System.out.println("ResultSet in empty in Java");
}
else {
do {
String id = rs.getString(1);
String fName = rs.getString(2);
String lName = rs.getString(3);
System.out.print(id +" ," + fName + ", " + lName);
System.out.println();
} while (rs.next());
}
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
try
{
conn.close();
st.close();
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
A reduced version of your query is :
Select * from users
Where gender = 'F'
And interest1 = 'FISHING'
Or interest2 = 'FISHING'
However, AND has higher priority than OR, so this query is equivalent to :
Select * from users
Where ( gender = 'F' And interest1 = 'FISHING')
Or interest2 = 'FISHING'
What you need to do is add brackets, so :
Select * from users
Where gender = 'F'
And ( interest1 = 'FISHING' Or interest2 = 'FISHING')
By the way, you are also leaving yourself wide open to a SQL injection attack, by including the search terms directly in the SELECT statement ( see What is SQL injection? ).
Much better would be to get in the habit of always using a PreparedStatement.
I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.
I got a code, which is searching a whole database. Everything works fine, the only problem is, that I would like to post the whole tuple with integers and chars and so on.
package src;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Pattern;
/*
PATTERN MATCHING
*/
public class BigSearch {
public static void main(String[] args) {
try {
String keyword;
String schema = "public";
Boolean caseAware = true;
System.out.println("Insert the term we shall look for in the database.");
Scanner s = new Scanner(System.in);
keyword = s.nextLine();
System.out.println("Do you want the search to be case sensitve "
+ "\n1 - case sensitive"
+ "\n0 - case insensitive");
int caseAwareInt = s.nextInt();
while (caseAwareInt != 0 && caseAwareInt != 1) {
System.out.println("You need to enter 1 or 0. Enter again!");
caseAwareInt = s.nextInt();
}
if (caseAwareInt == 1) {
caseAware = true;
} else if (caseAwareInt == 0) {
caseAware = false;
}
System.out.println("Your search is now case ");
if (caseAware) {
System.out.println("sensitive!");
}
if (!caseAware) {
System.out.println("insensitive!");
}
String like = "";
if (caseAware) {
like = "LIKE";
} else {
like = "ILIKE";
}
Connectivity connectivity = new Connectivity();
conn = connectivity.getConnection();
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
Statement stmt5 = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
ResultSet tablenames = stmt2.executeQuery("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
rs.next();
int counttables = rs.getInt(1);
System.out.println("Tabellen im Schema: " + counttables);
int appearance = 0;
int diftables = 0;
for (int i = 0; i < counttables; i++) {
tablenames.next();
ResultSet columnnames = stmt3.executeQuery("SELECT * " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
ResultSet rss = stmt4.executeQuery("SELECT COUNT(*) " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
rss.next();
int countcolumns = rss.getInt (1);
System.out.println("Spalten in der Tabelle " + tablenames.getString(1) + ": " + countcolumns);
int count = 0;
for (int i2 = 0; i2 < countcolumns; i2++) {
columnnames.next();
columnnames.getString(1);
System.out.println("Spaltenname: " + columnnames.getString(1));
System.out.println("Tabelle: " + tablenames.getString(1));
ResultSet containsString;
containsString = stmt5.executeQuery("SELECT * "
+ "FROM " + tablenames.getString(1)
+ " WHERE " + columnnames.getString(1) + " " + like + " '%" + keyword + "%'");
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
}
if (count > 0) {
diftables ++;
}
}
System.out.println("The keyword was found " + appearance + " times in " + diftables + " different tales.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I think the problem is the following code:
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
So there I am saying getString(1), but I would like to print the full row and because all table have different variable types and different numbers of it, I can't say getString 1, 2, 3, and so on. .getRow doens't work is well.
Any ideas?
There is no way to get all values at once. You need to get them yourself column-by-column. You could use getObject and let the default toString() of that object handle it. The other option is to use the ResultSetMetaData to get the right type of processing, but this might be too complex for your needs.
The getRow doesn't work, because it "Retrieves the current row number.".
Some JDBC drivers will support getString for most datatypes and handle the conversion for you.
I am trying to get the first column (column id and get the associated first and last name). I have tried multiple things but unable to get it to work.
It returns me with error CUSTOMERID not found.
public String getCustomerUsingId(int id) {
String firstName = null;
String lastName = null;
Statement stmt = null;
String getCustomerQuery = "SELECT FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
stmt.execute(getCustomerQuery);
ResultSet rs = stmt.getResultSet();
if(rs.next()){
id = rs.getInt("CUSTOMERID");
System.out.println("id is:" + id);
if(id == -1){
System.out.println("value is true");
firstName = rs.getString(2);
lastName = rs.getString(3);
System.out.println("First Name :" + firstName);
System.out.println("First Name :" + lastName);
}
}
}
I am using H2 as database and this is what is looks like
CUSTOMERID FIRSTNAME LASTNAME
1 P S
2 K S
This is how I have created the table
String customerSqlStatement = "CREATE TABLE CUSTOMERS " + "(customerId INTEGER NOT NULL IDENTITY(1,1) PRIMARY KEY, " + " FirstName VARCHAR(255), " + " LastName VARCHAR(255))";
You also need to explicitly include the column name in the select query.
So, the variable getCustomerQuery should be something like
String getCustomerQuery = "SELECT CUSTOMERID,FIRSTNAME,LASTNAME FROM CUSTOMERS WHERE CUSTOMERID ='"
+ id + "'";
This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 9 years ago.
I'm trying to create a query within a results set loop but I keep getting the error "Before start of result set". I've attempted many different methods but they keep coming up with the same error.
Can someone help me out here?
String insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,"; //Primary Key.
String PlannetSchemeCode = "";
int ResponcibleAuthorityID = 0;
Statement stmt = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
ResultSet resultsSet = stmt.executeQuery("SELECT * FROM planning_scheme");
Statement insideStatement = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
//Loop though each planning scheme and create the data for each field.
while (resultsSet.next())
{
PlannetSchemeCode = "'" + resultsSet.getString("ps_code") + "'";
//Planning Scheme Primary Key
insertSQL += PlannetSchemeCode + ",";
/*
//Responsible Authority ID
insertSQL += "'" + String.valueOf(
ResponcibleAuthorityID = MySQLUtil.getResults(
ConnectionDetails.Database_Connection_PPARSDB,
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
)
.getInt("resp_authority_id")
) + "'";
*/
ResultSet insideResultsSet =
insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
//ERROR HERE, some reason results set is getting set wrong??
//Error here, this current results set is resetting the Results set.
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
//Total_Received_CM
//Add the rest of the values temporary.
int FeildsAdded = 3;
for(int i = 1 + FeildsAdded; i < 458; i++)
{
insertSQL += String.valueOf(0) + ",";
}
//Insert date and end SQL string.
insertSQL += "NOW()";
insertSQL += ")";
System.out.println(insertSQL);
//Do Insert in PPARS.
//stmt.executeQuery(insertSQL);
//Reset the SQL String for the new Row.
insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,";
}
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
You need to call ResultSet#next() before you can read the returned data.
ResultSet insideResultsSet = insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
if (insideResultsSet.next()) {
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
// etc...
}