ORA-00923: FROM keyword not found where expected in SeleniumWebDriver - java

I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}

3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.

Related

While ResultSet is not executing?

I am trying to call two sets of data from two different tables to display in a JTextArea (jtaDisplay). The first table (emp_db) will get the employee number, name and surname. The second table (sec_clearance) will get the employee security clearance level.
The method is placed in the constructor so it will execute when the frame starts up, but whenever I run the frame it does not display the data. No error messages come up and the stack trace doesn't display any error messages.
I placed a JOptionPane in various places inside the method to see where the problem lies exactly and found that the while(rs.next()) statement is not executing as the JOptionPane displays outside the while statement but not inside it.
Here is the code I currently have:
try
{
String user = txtEmpTitle.getText();
String encuser = encrypt(user); //encrypting employee number with AES to read in database
String getEmpNum = "Select * from emp_db where emp_num = '" + encuser + "'";
String getSecLevel = "select secLevel from sec_clearance where emp_num = '" + encuser + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_database","root","pass123");
Statement stmt=conn.createStatement();
Statement stmt2=conn.createStatement();
ResultSet rs = stmt.executeQuery(getEmpNum);
ResultSet rs2 = stmt2.executeQuery(getSecLevel);
while(rs.next() && rs2.next())
{
String empNum = rs.getString("emp_num");
String empName = rs.getString("fname");
String empSname = rs.getString("sname");
String empSecLevel = rs2.getString("secLevel");
//decrypting data in database
String decNum = EmpEditDB.decrypt(empNum);
String decName = EmpEditDB.decrypt(empName);
String decSname = EmpEditDB.decrypt(empSname);
String decSecLevel = EmpEditDB.decrypt(empSecLevel);
jtaDisplay.setText("Employee number: " + decNum +
"\nEmployee name: " + decName + " " + decSname +
"\nSecurity clearance: " + decSecLevel);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
How can I get the code in the while statement to execute and display data in the JTextArea?
only if you have record ,it will come into while loop.Better use preparedstatement for dynamic value setting.For debugging purpose try to print your query in debugging and copy the query and execute in sql tool for checking whether any records.

ORA-00917: missing comma - Insert query failed

I'm trying to create insert query in JSP page as follows
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:" + "XE", "hr","hr");
if (connection != null)
{
statement = connection.createStatement();
String q2 = "INSERT INTO HR.tweets (";
q2 = q2 + "DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER)";
q2 = q2 + "VALUES (";
q2 = q2 + "(select SYSDATE from dual),";
q2 = q2 + "'" + tweet.getUser().getScreenName() + "'" + ",";
q2 = q2 + "'" + tweet.getText() + "'" +",";
q2 = q2 + "'" + finalstring + "')";
statement.execute(q2);
statement.close();
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
At statement.execute(q2) I'm getting ORA-00917: missing comma error.
The following query is created in a code :
INSERT INTO HR.tweets (DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER)VALUES ((select SYSDATE from dual),'Dannazxcv','RT #HugotInhinyero: Wish we could turn back time to the good old days. When our mama sings us to sleep but now we're stressed out.🎶🎶
#engin…','hugotinhinyero turn back time good days. mama sing sleep we're stress out. engin' )
Please help me.
Your SQL insert has an syntax error since one of your parameters contains a ':
'hugotinhinyero turn back time good days. mama sing sleep we're stress out. engin'
To avoid this kind of errors, don't build SQL strings manually, but use a PreparedStatement and parameters instead:
String insert = "INSERT INTO HR.tweets (DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER) " +
" VALUES ((select SYSDATE from dual),?,?,?)";
PreparedStatement stmt = connection.prepareStatement(insert);
stmt.setParameter(1, tweet.getUser().getScreenName());
stmt.setParameter(2, tweet.getText());
stmt.setParameter(3, finalstring);
stmt.executUpdate();
Use PreparedStatement instead of Statement.
Your query will always fail if any of your field will contain quote character (').
Besides, your query is vulnerable to SQL injection attack, while PreparedStatement guards against a such attack.
Details on PreparedStatement can be found in this tutorial:
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
This is a very very basic knowledge so I dont't explain it here.
The problem here is that you are using special characters, which causes the statement sent through to the database to be invalid.
Try using a prepared statement like this...
PreparedStatement pstatement = null;
Connection connection = null;
try
{
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:" + "XE", "hr","hr");
if (connection != null)
{
pstatement = connection.prepareStatement("INSERT INTO HR.tweets (DATE_TIME,USER_NAME,TWEET_BEFORE,TWEET_AFTER) VALUES ((select SYSDATE from dual),?,?,?)");
q2 = q2 + "'" + tweet.getUser().getScreenName() + "'" + ",";
q2 = q2 + "'" + tweet.getText() + "'" +",";
q2 = q2 + "'" + finalstring + "')";
pstatement.setString(1, tweet.getUser().getScreenName());
pstatement.setString(2,tweet.getText());
pstatement.setString(3, finalstring);
pstatement.execute();
}
}
catch (SQLException e)
{
e.printStackTrace();
}finally{
pstatement.close();
connection.close();
}
...prepared statements usually take care of malformed strings and invalid quotes sent to the DB.
As mentioned by #wero, the issue with the query is that it contains a quote ('). To escape it you can use a backslash (\).
Eg: we\'re
However like other's have suggested, its safer to use prepared-statements which also take care of guarding against sql-injection as a bonus !

LIKE Statements Not Working in Java SQL Prepared Statement

I'm working on creating a Java interface for an SQL database. I'm using prepared statements to perform the search queries, however they only work with "=" statements and not with LIKE statements.
The first sample code using "=" works successfully. The second sample, using a LIKE statement, does not work and just returns empty.
WORKS:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName = ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
DOESN'T WORK:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
Any help is much appreciated, also if you could explain it to me keeping in mind I'm very new to Java and don't have a lot of programming experience yet.
The rest of my search button's code:
private void button_SearchActionPerformed(java.awt.event.ActionEvent evt) {
String FirstName = textField_FirstName.getText();
String LastName = textField_LastName.getText();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:Alumni_DB");
Statement st=con.createStatement();
con.commit();
System.out.print(FirstName + " ");
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setString(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
String aUID="",aFName="",aLName="",aMInitial="",aHomePhone="",aCellPhone="";
while(rs.next())
{
aUID=rs.getString(1);
aFName=rs.getString(2);
aLName=rs.getString(3);
aMInitial=rs.getString(4);
aHomePhone=rs.getString(5);
aCellPhone=rs.getString(6);
System.out.println("UID " + aUID + " First Name " + aFName + " Last Name " + aLName + " Middle Initial " + aMInitial + " Home Phone " + aHomePhone
+ " Cell Phone " + aCellPhone);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
Note: Anything with the prefix 'a' is referring to a database column

Sql Syntax error unknown field list but looking for wrong field?

So I created the following function to write to a database:
public static void updateBuyer(String ID, String name, Location latlong) {
float lat = latlong.latitude;
float lon = latlong.longitude;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
// conn =
// DriverManager.getConnection("jdbc:mysql://localhost:3306/testdatabase?user=testuser&password=testpassword");
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String sql = "UPDATE Buyer " + "SET latitude ="
+ Float.toString(lat) + " WHERE idBuyer in (" + ID + ")";
String sql2 = "UPDATE Buyer " + "SET longitude ="
+ Float.toString(lon) + " WHERE idBuyer in (" + ID + ")";
String sql3 = "UPDATE Buyer " + "SET Name =" + name
+ " WHERE idBuyer in (" + ID + ")";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
conn.close();
} catch (Exception e) {
System.err.println(e);
}
}
Lets say I passed the following parameters:
(12,craigs,location object)
Now when I run the function I get the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'craigs' in 'field list'
12 is the ID i retrieved from the databases earlier,
craigs is the random name I am trying to insert, and
location object is just a set of coordinates (lat,long)
Which leads me to think that it is looking for a field called "craigs" in the table for some reason, but why would it do that?
The problem is that you've got SQL like this:
UDPATE Buyer SET Name = craigs WHERE idBuer in (Whatever)
That's trying to copy the value from a column named "craigs".
Now you could just add apostrophes - but don't. Instead, use parameterized SQL with a prepared statement. That way you'll avoid SQL injection attacks, your code will be simpler, and you'll avoid unnecessary string conversions which can cause problems, particularly with date values.
Additionally, you only need a single statement, which can update all three columns:
String sql = "UPDATE Buyer SET Name=?, latitude=?, longitude=? WHERE idBuyer=?";
try (PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setString(1, name);
statement.setFloat(2, lat);
statement.setFloat(3, lon);
statement.setString(4, ID);
statement.executeUpdate();
}
(Note that I've assumed you're actually only trying to update a single buyer - it's not clear why you were using IN at all. Also note that I'm using a try-with-resources statement, which will automatically close the statement afterwards.)
Additionally, I would *strongly *advise you to avoid just catching Exception. Catch SQLException if you must - but you'd actually probably be better letting it just propagate up the call stack.

ResultSet.next() Throwing SQLException: Result Set Closed

I've tried to debug the code and read the Oracle doc and I don't see any reason why the result set would be closed.
Statement statement = DatabaseConnector.connect();
String sql = "Select * from Room where Room_Type like '*"+roomType+"*' "+availability;
boolean foundResults = statement.execute(sql);
if(foundResults){
ResultSet rs = statement.getResultSet();
StringBuilder row = new StringBuilder();
if(rs!=null){
while(rs.next()){
RE: SQLException
I'm not quite sure what DatabaseConnector is supposed to do in the question code, but the following test code works for me.
RE: Wildcard character
When using the LIKE operator in a query from within the Access application itself then the asterisk * is the wildcard character to use. When querying an ACE (Access) database from some other application one needs to use the "standard" percent % wildcard character. Note that the following code uses %; using * won't work here.
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
"Dbq=C:\\Users\\Public\\Database1.accdb;");
String RoomTypeToMatch = "suite";
PreparedStatement s = conn.prepareStatement(
"SELECT Room_No, Room_Type " +
"FROM Room WHERE Room_Type LIKE ?"
);
s.setString(1, "%" + RoomTypeToMatch + "%");
s.execute();
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("[Room_No]: " + rs.getString(1) +
", [Room_Type]: " + rs.getString(2));
}
}
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
SQL LIKE wildcard charcaters are represented as % not *
String sql =
"Select * from Room where Room_Type like '%"+roomType+ "%' "+availability;
Aside: Always use a PreparedStatement to project against SQL Injection attacks

Categories