Java - Search Oracle DB for a row with spaces (ORA-00920) - java

I am trying to execute a select query from Java, the tricky part is that both the condition and the column have a String with spaces :
String query = "select rule_name "+
" from rules " +
" where rule_name = " m_rule; //rule_name = str tf //m_rule = str tf
So the query output :
select rule_name
from rules
where rule_name = str tf
The error code - ORA-00920 - I belive it is because of the spaces.
Is there any way to fix this?

The error that you are facing basically means :
ORA-00920: invalid relational operator
This is the blank that is causing the issue. Your Java code should enclose the conditional parameter in quotes:
String query = "select rule_name "+
" from rules " +
" where rule_name = '" + m_rule + "'";
Hope this will help!

Related

how to update a sql varchar column using JAVA handle createStatement INNO DB

I need to update my columns using JAVA Handle and create statement, but from what I have researched I need to be using batch if its all (or most) of the columns I desired to update?
This is the code i've written thus far:
private int deletePlayer(Handle handle, String username, String table) {
logger.debug("Deleting from table " + table);
String sqlCommand;
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1 "
+ "SET exp = 0 "
+ "SET prof = '' "
+ "SET guild = '' "
+ "SET varname = '' "
+ "WHERE name = :username", table);
handle.createStatement(sqlCommand)
.bind("username", username)
.execute();
return 1;
}
I broke it up to try and pinpoint the problem and found that the MySQL Command:
sqlCommand = String.format("UPDATE %s SET varname = '' WHERE name = :username", table);
And the like is not working. This is more than likely because of the string/char concatenation.
Also, should I be using batch instead?
Stack Trace: [Ljava.lang.StackTraceElement;#15b2043
Please, if you are going to make this post down please tell me why and I will be more than happy to fix it to your liking, or clarify, so that it adheres to the forum conduct/terms of service/ et cetera.
I think you missed the comma between keyword set to update DB values.
sqlCommand = String.format("UPDATE %s SET rank = 1 "
+ "SET level = 1, "
+ "SET exp = 0, "
+ "SET prof = '', "
+ "SET guild = '', "
+ "SET varname = '' "
+ "WHERE name = :username", table);

fetch value from SQL query list

So i just wrote down this SQL query and i am trying to capture the value of rest_id in query.list(). However, this is giving the value as [1] . I want just 1 without the braces. How do i do it? Please check the code below for reference:
String sql1 = "select rest_id from rest_details where rest_name = '" + nameclicked + "' and rest_location = '" +locclicked + "'" ;
SQLQuery query1 = session.createSQLQuery(sql1);
System.out.println("sql1 " + query1.list());
Use below code to get the element inside list:
System.out.println("sql1 " + query1.list().get(0));
This always returns only the first element from the list.
Replace
System.out.println("sql1 " + query1.list());
By :
for(String id : query1.list() ) System.out.println("sql1 " + id);

Trouble with a line of SQL in my java program

So the program is the connecting to a .mdb file as our data base. I have written all the other code to the program and know it works fine but I am now having trouble with a complex SQL statement being passed as a parameter to a createQuery(Sring, int) method.
There are two tables
Person, which has Name, Id, City, State
Classes, which has Id, Course, Grade
The intended purpose of this line is to print out "Name and Id" from a table of Persons and also print "Course and Grade" from the Classes table. The query only prints entries with matching Id's(Person.Id = Classes.Id), in a specific Course('CSC 225'), and that have a Grade > 70.
We never were taught the SQL statements in any depth so my basic understanding has concocted the following lines of code.
String s = "SELECT " + personTableTitle + ".Name, " + personTableTitle + ".Id, " +
classesTableTitle + ".Course, " + classesTableTitle + ".Grade FROM " +
personTableTitle + " " + classesTableTitle + " WHERE " +
personTableTitle + ".ID = " + classesTableTitle + ".Id AND " +
"Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
personTableTitle + ".Id = ? AND " + classesTableTitle + ".Id = ?";
System.out.print(s); // Double check of my SQL Statement before passing
db.createQuery(s, 4);
I have been playing with this SQL statement since Wednesday night and haven't been having much luck.
I only see two problems. Sql needs commas between the table names in the FROM clause, i.e. ...FROM table1, table2 WHERE.... So change your line to
personTableTitle + ", " + classesTableTitle + " WHERE " +
This next one might not be a problem, but it's a good idea to include the table name in front of every field reference.
classesTableTitle + ".Course = 'CIS 225' AND " + classesTableTitle + ".Grade > 70 AND " +
You should definitely try your query directly on the database (console or GUI). Once your query is valid, you'll be able to translate it very quickly back into Java.
Otherwise, it's good practice to add an alias to tables; for example:
select *
from Person P, Classes C
where P.Name = 'joe' and P.id = C.id
You may also need to do an outer join to get your data (look at how to do joins for your database).
Here's what I would suggest for SQL code
String s = "SELECT P.Name, P.Id, ";
s = s + "C.Course, C.Grade ";
s = s + "FROM Person P ";
s = s + "JOIN Classes C ";
s = s + "ON P.ID = C.ID ";
s = s + "WHERE Course = 'CIS 225' AND C.Grade > 70;";
I split up each assignment into its own line.
Solved it everyone, thanks for the help.
I started rewriting it using the suggestions posted and came up with this as the string:
String s = "SELECT Person2.Name, Person2.Id, Classes.Course, Classes.Grade FROM Person2, Classes WHERE Classes.Id = Person2.Id AND Classes.Course = 'CIS 225' AND Classes.Grade >70";
It works so I can make it more presentable now. The reason I am using my variable names from java in the original post was that is what the teacher wanted. She is very stubborn and has taken off points from my material for things as simple as writings += whatever; instead of s = s + whatever;

How to make select query with StringTokenizer?

I'm trying to make a query with selected fields for final user from view (JSP) to controller, but I don't know how.
For example, I have this parameters from view (JSP)
IDUSER,>,2,OR,USERNAME,=,'KURT'
So, I'll want to have something like this,
SELECT IDUSER, USERNAME FROM TABLE_NAME WHERE IDUSER > 2 OR USERNAME = 'KURT'
but I have next result
SELECT null FROM TABLE_NAME WHERE IDUSER > 2 OR USERNAME = 'KURT'
I'm parsing string with StringTokenizer class, where query is: String query = request.getParameter("data"); and data is IDUSER,>,2,OR,USERNAME,=,'KURT'.
StringTokenizer field = new StringTokenizer(query, ",");
nFields = field.countTokens();
System.out.println("nFields: " + nFields);
String[] fields = new String[nFields];
for(int i = 0; i < fields.length; i++) {
while(field.hasMoreTokens()) {
fields[i] = field.nextToken();
}
System.out.println("fields[i]: " + fields[i]);
myQuery = "SELECT " + fields[i] + " FROM "+tableName+ " WHERE ";
System.out.println("myQuery 1: " + myQuery);
}
StringTokenizer token= new StringTokenizer(query, "|,");
while(token.hasMoreTokens()) {
myQuery = myQuery + token.nextToken() + " ";
}
System.out.println("QUERY RESOLVED: " + myQuery);
PLEASE HELP ME
Here is the solution after minor tweak in your query (redefined the separators)
public static void main(String[] args) {
// Redefine the separators as single , separators is difficult to process
//You would need to define possible operators like this (#OR# , #AND# ) ,surrounded by special characters to identify.
String query ="IDUSER_>_2#OR#USERNAME_=_'KURT'";
String tableName="TESTTABLE";
String operator=null;
//you can choose operator conditionally
if(query.contains("#OR#")) operator="#OR#";
// if(query.contains("#AND#")) operator="#AND#";
//Used split instead of Tokenizer.
String cols[]= query.split(operator);
String myQuery = "SELECT ";
String select="";
for(String col:cols){
if(!select.isEmpty()){
select+=" , ";
}
// Only the first element is retrieved (for select)
select+=col.split("_")[0];
}
myQuery+=select+" FROM "+tableName+ " WHERE ";
// Removes all special charecters (like, # and _ with white space)
String subQuery = query.replaceAll("#", " ");
subQuery=subQuery.replaceAll("_", "");
myQuery+=subQuery;
System.out.println("QUERY RESOLVED: " + myQuery);
}
Note : ',' is replaced with '_' and operators are surrounded by '#'
Cheers!!
I think the problem is this line in your while loop:
myQuery = "SELECT " + fields[i] + " FROM "+tableName+ " WHERE ";
This will keep changing the value of myQuery as the while loop executes.
Maybe you need to replace this with:
myQuery = "SELECT " + fields[0] + " FROM "+tableName+ " WHERE ";
break;
I am assuming your selection criteria is the first field in the parameter from your view.
Do not see where does IDPERFIL come from. Also, I don't like this:
while(field.hasMoreTokens()) {
fields[i] = field.nextToken();
}
That will iterate tokenizer to the end, and stop at last element. I am sure you don't want this. Fix that, tell where IDPERFIL come from, and then, maybe, you'll understand answer by yourself. Otherwise, I'll try to help further.

Quick Java SQL problem

My code:
String sql = "SELECT Publisher.Name, Book.Title, ShopOrder.OrderDate, SUM(OrderLine.Quantity) AS No_Books, "
+ "SUM(OrderLine.UnitSellingPrice * Orderline.Quantity) AS Total_Price"
+ "FROM Publisher, Book, OrderLine, ShopOrder"
+ "WHERE OrderLine.BookID = Book.BookID AND ShopOrder.ShopOrderID = OrderLine.ShopOrderID AND Publisher.PublisherID = Book.PublisherID AND Publisher.PublisherID = " + id
+ "GROUP BY book.title, publisher.name, ShopOrder.OrderDate"
+ "ORDER BY ShopOrder.OrderDate, Book.Title";
Resulting error:
syntax error at or near "Publisher" at char position 166 (Just after the FROM clause)
Theres spaces missing
Your strings is
...S Total_PriceFROM Publisher, Book, OrderLine, ShopOrderWHERE O...
You should use:
String sql = "SELECT Publisher.Name, Book.Title, ShopOrder.OrderDate, SUM(OrderLine.Quantity) AS No_Books, "
+ " SUM(OrderLine.UnitSellingPrice * Orderline.Quantity) AS Total_Price"
+ " FROM Publisher, Book, OrderLine, ShopOrder"
+ " WHERE OrderLine.BookID = Book.BookID AND ShopOrder.ShopOrderID = OrderLine.ShopOrderID AND Publisher.PublisherID = Book.PublisherID AND Publisher.PublisherID = " + id
+ " GROUP BY book.title, publisher.name, ShopOrder.OrderDate"
+ " ORDER BY ShopOrder.OrderDate, Book.Title";
When you concatenate those strings there is no space between Total_Price and FROM.
And in other lines similarly. I always end and start a quoted SQL fragment with a space.
You need spaces either at the end of your lines or at the beginning. The resulting string would look like: ...AS Total_PriceFROM Publisher...

Categories

Resources