Oracle query execution error [duplicate] - java

I'm having an issue with my query not working. This is the command variable.
When it executes it should be retrieving the tuples that have BSc as their degree. I have tested this in oracle directly and the query returns these. It is identical to the command statement.
When I print out command, the line looks exactly the same as my command that worked in oracle.
SELECT distinct fname, lname, student_id FROM student where degree='BA';
Yet, it should be printing out to the screen. The tables are loaded into oracle already.
I've been racking my brain with this issue but can't seem to find a fix!
The error I keep getting is:
ORA-00911: invalid character
What I do is I store in degree the result from scanner which is a string. So concatenating it in the command variable shouldn't make an issue -- the query looks identical to what works in oracle.
Could it be because it wants a char instead of a string? If it does, then how would I get it to make "BSc" as a char? Concatenating chars sounds dumb.
Relevant code below:
private String getDegree() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter degree code (either BA or BSc)");
return scan.next();
}
//get the degree name
String degree = getDegree();
//get statement and execute appropriate select
Statement stmt = con.createStatement();
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
System.out.println(command);
ResultSet result = stmt.executeQuery(command);
//determine number of columns
ResultSetMetaData metadata = result.getMetaData();
int columns = metadata.getColumnCount();
//print heading
System.out.println("\nFNAME LNAME STUD_ID");
System.out.println("====================================");
//loop through result and print columns
while (result.next()){
for (int i=1; i <=columns; i++){
System.out.print(result.getString(i)+spaces(15-result.getString(i).length()));
}
System.out.println();
}
`

In JDBC your SQL statement should not be terminated by semicolon.
Change
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
to
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "'";

Related

cannot identify the missing right parenthesis

Attempted to run the query from extracting data from a specific website, but picking up
ORA-00907: missing right parenthesis instead.
public static void build(){
Connection con = null;
ResultSet rs = null;
Statement stms = null;
String buildXML ="";
String list = lists.stream().collect(Collectors.joining("','"));
try {
<<<database>>>
<<<connection>>>
rs = stmt.executeQuery("select name, type, dob, age, height, weight from peopleH where name in ('" + list + "') and age !=0 and dob !=0"); <-- *error here?!?*
while(rs.next()){
for(int i=0; lists.size() > i; i++){
if(<<does not contain the name>>){
<<<do this>>>
}
else {
<<<do that>>>
}
}
}
}
catch(){
} finally{
}
}
What's meant to happen is that when data is filter and extracted via selenium (which is stored in an arrayList). The query above will query the arraylist and compare with the database against what is display on the selenium browser.
however the query above is pitching out missing right parenthesis...
I can't seem to find the issue here as last checked there is no addition , or invalid logic (in (***) and 'and' statement).
the data being filtered from selenium is printing out as expected
e.g john, sam, smith, mary, lili, happy
if placed in query it will be something like this
rs = stmt.executeQuery("select name, type, dob, age, height, weight from peopleH where name in ('john','sam','smith','mary','lili','happy') and age !=0 and dob !=0");
to something like this
rs = stmt.executeQuery("select name, type, dob, age, height, weight from peopleH where name in ('" + list + "') and age !=0 and dob !=0");

SQL ResultSet is empty despite having a row returned in tests

I am building a simple program for a library database system in Java where patrons can borrow and return books. The database has 4 tables: Book, Author, Patrons, and AuthorIds. I'm using the SQL statement below to retrieve 1 row of data that includes everything plus a column that counts how many books the patron has already borrowed. The problem is that the program never goes into the while(res.next()) loop and I think it's because the result set is empty. The test print doesn't get printed and membID doesn't get changed to the MemberID of the patron.
But when I try that same SQL statement on db browser on the same database it returns 1 row as expected with the BooksBorrowed column. All of my other ResultSet while loops have worked and returned rows with other SQL statements, it's just this one that doesn't and I don't know why.
public void borrowBooks(String fName, String lName, Scanner input) throws SQLException {
//first find out how many books the user has already borrowed
int booksBorrowed = 0;
int membID = 1; //this will be used for later
sql = "select *, Count(MemberID) AS BooksBorrowed\r\n" +
"FROM Book\r\n" +
" JOIN AuthorIds USING (BookID)\r\n" +
" JOIN Author USING (AuthorID)\r\n" +
" JOIN Patron USING (MemberID)\r\n" +
"WHERE PatronFirstName LIKE ? AND PatronLastName LIKE ?\r\n" +
"GROUP BY MemberID\r\n" +
"ORDER BY BookID ASC";
PreparedStatement stmt = connection.prepareStatement( sql );
stmt.setString(1, fName);
stmt.setString(2, lName);
ResultSet res = stmt.executeQuery();
while(res.next()) {
booksBorrowed = res.getInt("BooksBorrowed");
System.out.println(res.getInt("MemberID"));
System.out.println("Test");
membID = res.getInt("MemberID");
}
if(booksBorrowed >= 2) {
System.out.println("You have already borrowed the maximum amount of 2 books. Return books to borrow more");
}
I figured it out and it was that I should have gotten the memberID in a separate query because I was trying to change it to the corresponding patron in the same query as I was trying to get the number of books borrowed. The problem was that if the patron didn't have any books borrowed, then the result set would be empty and the memberID wouldn't change from what it was temporarily initialized as. This memberID was later inserted into the table for when a book was borrowed so it would be the temporary stand in each time and not the actual memberID of the patron, so the patron would have no books under their name as borrowed.

Getting Syntax error in SQL query in JDBC

I am getting a syntax error, but I am mostly sure I am doing everything right. Could you take a look?
String ORDER, DROP, CAR;
String Statement = "INSERT INTO WORKORDER"
+ "(ORDER, DROPOFFDATE, COMPLETIONDATE) VALUES "
+ "( ?, ?, null);";
//JOptionPane.showMessageDialog(frame, Statement, "Daisy Imports", 3);
try {
PreparedStatement PST = connection.prepareStatement(Statement);
ORDER = JOptionPane.showInputDialog("Please assign a order number for this order");
int ORDERi = Integer.parseInt(ORDER);
DROP = JOptionPane.showInputDialog("Please Enter the date the car was dropped off (YYYY-MM-DD)");
CAR = JOptionPane.showInputDialog("Enter the VIN for the car this work order is for");
PST.setInt(1, ORDERi);
PST.setString(2, DROP);
PST.execute();
Try getting rid of the semicolon at the end of your prepared statement.
Edit: The problem was that "ORDER" is a reserved word.

Replace Parameters in SQL query text with XXXXX

I m writing a small utility that captures and logs SQL statements, but will have to remove sensitive data from the Query text and replace with with some dummy text (i.e:XXXXX).
What is a good way to parse the SQL query in java and replace parameters value?
for example:
replace
SELECT NAME, ADDRESS, .... FROM USER WHERE SSN IN ('11111111111111', '22222222222222');
with
SELECT NAME, ADDRESS, .... FROM USER WHERE SSN IN (?, ?);
Using JSQLParser (V0.8.9) this is a solution for your problem:
String sql ="SELECT NAME, ADDRESS, COL1 FROM USER WHERE SSN IN ('11111111111111', '22222222222222');";
Select select = (Select) CCJSqlParserUtil.parse(sql);
//Start of value modification
StringBuilder buffer = new StringBuilder();
ExpressionDeParser expressionDeParser = new ExpressionDeParser() {
#Override
public void visit(StringValue stringValue) {
this.getBuffer().append("XXXX");
}
};
SelectDeParser deparser = new SelectDeParser(expressionDeParser,buffer );
expressionDeParser.setSelectVisitor(deparser);
expressionDeParser.setBuffer(buffer);
select.getSelectBody().accept(deparser);
//End of value modification
System.out.println(buffer.toString());
//Result is: SELECT NAME, ADDRESS, COL1 FROM USER WHERE SSN IN (XXXX, XXXX)
This replaces all found String values within your SQL. To replace other types of data e.g. Long values, override the corresponding visit method in ExpressionDeParser.
Don't use regexp in this case. It turns out quickly to be hard maintainable.
The correct answer depends on how much you want to replace. Something like:
[0-9]{3}-?[0-9]{2}-?[0-9]{4}
will replace social security numbers pretty well. I always take regex code to
regexpal.com
to tweak it and work out bugs.
If you need to replace tons of sensitive information though, and if there are a lot of cases, definitely start looking into using a parser to parse the SQL query string. (such as jsqlparser, as Anirudh recommended.)
String sqlDebit = select * from table where and billing_cycle_start_date between :startDate and :endDate
java:
sqlDebit= sqlDebit.replaceAll(":startDate ", ""+startDate).replaceAll(":endDate", ""+endDate);
With prepare statement you can replace "?" in your query string with your value. Use number to specify which "?" you are referring too. They go by order from right to left.
For example: "SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ? and FirstName = ?"
pstmt.setString(1, "LastNameValue");
pstmt.setString(2, "FirstNameValue");
see full example below:
public static void executeStatement(Connection con) {
try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) {
pstmt.setString(1, "Smith");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}

how to count with database statement by using netbeans

I'm trying to count the input and match it with the data field in database then count the status and display the number of books that the input had borrowed.
Statement statement = conn.createStatement();
String sql = "SELECT COUNT(jtfMemberID.getText()) as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
ResultSet rs1 = statement.executeQuery(sql);
int personCount = 0;
if(rs1.next()) {
personCount = rs1.getInt("num");
jlbBookBorrow.setText(rs1.getString(personCount));
}else{
jlbBookBorrow.setText("0");
}
The text jtfMemberID.getText() will be interpreted literally in your SQL String. You need to extract it out:
String sql = "SELECT COUNT(" + jtfMemberID.getText() + ") as num FROM LOAN WHERE LOAN_STATUS='BORROWED'";
Also, to protect against SQL Injection attacks, consider using PreparedStatement.

Categories

Resources