Unable to retrieve first column - java

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 + "'";

Related

How do I filter search by entering all the column data on java-sql application?

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.

HSQL database user lacks privilege or object not found error try insert data into database

I try to read data from text file then insert into database but keep getting error.
Below is the code I am writing
Class.forName("org.hsqldb.jdbcDriver");
connection = DriverManager.getConnection("jdbc:hsqldb:TestDB", "sa", "123");
connection.prepareStatement("drop table people if exists;").execute();
connection.prepareStatement("create table people (id integer, name varchar(20) not null, picture varchar(20), detail varchar(40), gender varchar(5), age integer, state varchar(5), primary key(id));").execute();
String fileName = "/Users/da/Desktop/AP Assignment 2/people.txt";
BufferedReader br = new BufferedReader(new FileReader(fileName));
while (strLine != null) {
String data[] = null;
strLine = br.readLine();
data = strLine.split(",");
int id = Integer.parseInt(data[0]);
String name = data[1];
String picture = data[2];
String detail = data[3];
String gender = data[4];
int age = Integer.parseInt(data[5]);
System.out.println(age);
String state = data[6];
String sql = "insert into people(id, name, picture, detail, gender, age, state) values (" + id + "," + name + ", " + picture + ", " + detail + ", " + gender + ", " + age + ", " + state + ")";
connection.prepareStatement(sql).execute();
connection.commit();
}
br.close();
By attempting to embed the data values into your SQL string you have created an SQL Injection problem. For example, the code
int id = 1;
String name = "gord";
String sql = "INSERT INTO people (id, name) VALUES (" + id + ", " + name + ")";
System.out.println(sql);
prints
INSERT INTO people (id, name) VALUES (1, gord)
When we try to execute that statement the query parser recognizes 1 as an integer literal but it interprets gord as a column name, so we'll get a "user lacks privilege or object not found" error.
The solution is to use a parameterized query like this:
int id = 1;
String name = "gord";
String sql = "INSERT INTO people (id, name) VALUES (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, id);
ps.setString(2, name);
ps.executeUpdate();

SQLITE delete method in Java

I have a method that should delete a Person(a row) from my database.
I am getting the error message that I created in the catch. I just started working with Databases and I have mostly been piecing together different techniques. I'm not sure what to do
public static void deletePerson(String firstNameOfPersonToDelete, String lastNameOfPersonToDelete) {
Statement stmt = null;
try {
// Create database connection
Connection c = DriverManager.getConnection("jdbc:sqlite:PERSON.db");
// Create Statement object
stmt = c.createStatement();
// Get person we're about to delete
String getPersonQuery = "SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM PERSON WHERE FIRSTNAME = '"
+ firstNameOfPersonToDelete + "' AND LASTNAME = '" + lastNameOfPersonToDelete + "'";
ResultSet rs = stmt.executeQuery(getPersonQuery);
String ssn = rs.getString("SSN");
String firstName = rs.getString("FIRSTNAME");
String lastName = rs.getString("LASTNAME");
String age = rs.getString("AGE");
String creditCard = rs.getString("CREDITCARD");
String deletePersonStatement = "DELETE FROM PERSON WHERE FIRSTNAME = '" + firstName + "' AND LASTNAME = '"
+ lastName + "'";
stmt.executeUpdate(deletePersonStatement);
System.out.println("The following record was deleted:\n" + ssn + "\n" + firstName + " " + lastName + "\n"
+ age + "\n" + creditCard);
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
} catch (SQLException e) {
e.printStackTrace(System.err);
System.out.println("Error: The person: \"" + firstNameOfPersonToDelete + " " + lastNameOfPersonToDelete
+ "\" was not found. No records were deleted.");
System.out.println("\nThe database contains the following records: ");
ArrayList<Object> myPeople = findAllPeople();
for (Object element : myPeople) {
System.out.println(element.toString());
}
}
}
java.sql.SQLException: no such column: 'SSN'Error: The person: "Fitzgerald Grant" was not found. No records were deleted.
at org.sqlite.jdbc3.JDBC3ResultSet.findColumn(JDBC3ResultSet.java:48)
at org.sqlite.jdbc3.JDBC3ResultSet.getString(JDBC3ResultSet.java:443)
at Test.deletePerson(Test.java:181)
at Test.main(Test.java:65)
SELECT SSN FIRSTNAME, LASTNAME, AGE, CREDITCARD FROM ...
^
This is the same as SSN AS FIRSTNAME, i.e., in the output of the query, the SSN column is renamed to FIRSTNAME. You apparently forgot a comma.
In any case, you got this error because there is no SSN column.
You have to ensure that you create this table with this column, or if you have an old database, that you add this column.

java/sql comparing two ints

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.

Defaults if player doesn't already have gems

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");
}

Categories

Resources