SQL Syntax in JAVA using JDBC - java

Statement stmt = null;
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
"FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
try {
con = getConnection();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
String heading1 = " Make"; String heading2 = " Model"; String
heading3 = " Year"; String heading4="Sold Status";
System.out.printf("%-20s %-20s %-20s %-20s\n", heading1, heading2,
heading3,heading4);
System.out.println("--------------------------------------------------------------------------\n");
while (rs.next()) {
String make = rs.getString("car.Make");
String model = rs.getString("car.Model");
int carYear = rs.getInt("car.Year");
boolean soldStatus = rs.getBoolean("car.Sold_Status");
String firstName = rs.getString("owner.First_Name");
System.out.printf("%-2s %-20s %-20s %-20s %-20s\n",
make, model, carYear,soldStatus,firstName);
}
System.out.println("\n\n");
} finally {
stmt.close();
}
The problem that I am having is a SQL syntax error, the syntax works in MySql workbench 6.0 but wont work in my Java App through JDBC, Im new to SQl and JDBC, I realize my result set may not be 100% for this query and that also may be the problem, its from a shared method, im more concerned with the SQL query statement in this case.

The problem is you are missing a space between the last selected column name and FROM. To paraphrase your query, you have:
String query = "SELECT ..., CarLot.OWNER.Last_Name"+ // oops, no space!
"FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
This error is very common, because it's hard to see a missing space at the end of a line, but there is a code style that I use to combat this - I put spaces at the start of the line, like this:
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name"+
" FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
Every line starts with quote-space, ie " ..., so now it's really obvious when a line-broken string is missing a space, and further because SQL is (generally) whitespace insensitive, you can put spaces at the end too without causing any problems.

Add a space before the FROM clause
String query = "SELECT CarLot.CAR.Make, CarLot.CAR.Model, CarLot.CAR.Year, CarLot.CAR.Sold_Status, CarLot.OWNER.First_Name,CarLot.OWNER.Last_Name" +
" FROM CarLot.CAR, CarLot.OWNER" +
" WHERE CarLot.CAR.Sold_Status = TRUE";
Aside: Consider using PreparedStatement to protect against SQL injection attacks

The first and second lines of your query don't have a space between them, so you have select ... CarLot.OWNER.Last_NameFROM CarLot... . Add the space and see what happens.

Related

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

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.

Prepared Statement setString adding unnecessary single quotes to String

Background
I am trying to set the contents of an ArrayList into an IN clause in a Db2 SQL statement. I am using the PreparedStatement to build my query. This is our coding standard.
What I tried #1
I researched a couple ways to achieve this. I first tried using the setArray() as show in this question: How to use an arraylist as a prepared statement parameter The result was I was getting a error of Err com.ibm.db2.jcc.am.SqlFeatureNotSupportedException: [jcc][t4][10344][11773][3.65.110] Data type ARRAY is not supported on the target server. ERRORCODE=-4450, SQLSTATE=0A502 After this roadblock, I moved on to #2
What I tried #2
I then tried using the Apache Commons StringUtils to convert the ArrayList into a comma separated String like I needed for my IN clause. The result is that this did exactly what I needed, I have a single String with all my results separated by a comma.
The problem:
The setString() method is adding single quotes to the beginning and end of my String. I have used this many times, and it has never done this. Does anyone know if there is a way around this, or an alternative using the PreparedStatement?? If I use String concatenation my query works.
Code (explained above):
List<String> selectedStatuses = new ArrayList<String>(); //Used to store contents of scoped var
//Get Contents of Checkbox which are in the form of a List
selectedStatuses = (List) viewScope.get("selectedStatuses");
String selectedStatusesString = StringUtils.join(selectedStatuses, ",");
.... WHERE ATM_DET_ATM_STAT IN (?)";
ps.setString(1, selectedStatusesString);
Log Value showing correct value of String
DEBUG: selectedStatusesString: 'OPEN','CLOSED','WOUNDED','IN PROGRESS'
Visual of incorrect result
The quotes at the beginning and end are the problem.
For an IN clause to work, you need as many markers as you have values:
String sql = "SELECT * FROM MyTable WHERE Stat IN (?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, "OPEN");
stmt.setString(2, "CLOSED");
stmt.setString(3, "WOUNDED");
stmt.setString(4, "IN PROGRESS");
try (ResultSet rs = stmt.executeQuery()) {
// use rs here
}
}
Since you have a dynamic list of values, you need to do this:
List<String> stats = Arrays.asList("OPEN", "CLOSED", "WOUNDED", "IN PROGRESS");
String markers = StringUtils.repeat(",?", stats.size()).substring(1);
String sql = "SELECT * FROM MyTable WHERE Stat IN (" + markers + ")";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
for (int i = 0; i < stats.size(); i++)
stmt.setString(i + 1, stats.get(i));
try (ResultSet rs = stmt.executeQuery()) {
// use rs here
}
}
Starting with Java 11, StringUtils is no longer needed:
String markers = ",?".repeat(stats.size()).substring(1);
Use two apostrophes '' to get a single apostrophe on DB2, according to the DB2 Survival Guide. Then call .setString().
To anyone else experiencing the issue with single quotes, I had to modify my function so that it doesn't use ? to set the value; instead, I just treat the entire query as a string:
public static void runQuery(String tableName, String columnName, int value, String whereName, String whereValue) {
try (Connection con = DatabaseConnection.getConnection()) {
try (PreparedStatement ps = con.prepareStatement("UPDATE " + tableName + " SET " + columnName + " = " + value + " WHERE " + whereName + " = " + "'" + whereValue + "'")) {
ps.executeUpdate();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
Hope this helps

How to use the "WHERE LIKE" command in SQL

I am trying to use the WHERE LIKE command in my program.
My Code
String searchCriteria = searchTextField.getText();
String searchCriteria1 ="'"+"%" + searchCriteria + "%"+"'";\
String query = "select ID,Priority,recipient,Sender,Label,Subject from Messages where Message like = '" + searchCriteria1 + "'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
Code Explained
1.What this code codes is get the input from the user.
2.Creates a string variable that contains the search condition and the "%" either side of the condition.
3.The last few lines execute the SQL query.
I am currently getting the error java.sql.SQLSyntaxErrorException: Syntax error: Encountered "=" at line 1, column 92. and not sure whats wrong with my statement.
Its most likely to be something very silly and small, I hope you can help.
Thank you
Seems as if you have single quotes twice over in the search criteria.
But you need to use prepared statement with bind parameters in this case.
You should use PreparedStatement like this:
String searchCriteria = searchTextField.getText();
String query = "select ID,Priority,recipient,Sender,Label,Subject from Messages where Message like ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, "%" + searchCriteria + "%");
ResultSet rs = pst.executeQuery();
Instead of putting your modulus(%) in your variable you can put it at the query itself and remove your equal(=) symbol. See below:
String searchCriteria1 =" + searchCriteria + ";
String query = "SELECT ID,Priority,recipient,Sender,Label,Subject FROM Messages WHERE Message LIKE '%" + searchCriteria1 + "%'";

SQL select statement with where clause

how would i write this sql statement without a hard coded value?
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name = 'john'");
// this works
rather have something like:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + name);
// Unknown column 'john' in 'where clause' at
// sun.reflect.NativeConstructorAccessorImpl.newInstance0...etc...
thanks in advance..
It is a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
Note that prepareStatement() is an expensive call (unless your application server uses statement caching and other similar facilities). Theoretically, it'd be best if you prepare the statement once, and then reuse it multiple times (though not concurrently):
String[] names = new String[] {"Isaac", "Hello"};
PreparedStatement statement = connection.prepareStatement("select * from myDatabase.myTable where name = ?");
for (String name: names) {
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
...
...
statement.clearParameters();
}
You are missing the single quotes around your string, your code corrected:
String name = "john";
String sql = "select * from myDatabase.myTable where name = '" + name + "'";
// Examine the text of the query in the debugger, log it or print it out using System.out.println
resultSet = statement.executeQuery(sql);
Print out / log text of the query before executing the query to see if it looks OK.
If you are going to do a lot of similar queries where only the constant changes, consider using prepared statements
this should work:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + "'" + name + "'");
you need to put quotes around the value ('john' instead of john)...
Try the following :
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where myTable.name = '" + name + "'");
Put quotes around your name value since it's a string.
"select * from myDatabase.myTable where name ='" + name + "'"

Java string interpreted wrongly in SQL

There is an string[] likely;
This array stores the name of column of database table dynamically while runtime.And the program understand the size of the likely in runtime.
Now to put this in sql query .I use a for loop for concatanation of string
for(int k=0;k<likely.length;k++)
{
temp1="\"+likely["+k+"]+\"='Likely' AND ";
temp=temp.concat(temp1);
}
if the size is 3 the final temp will look like
temp = " "+likely[0]+"='Likely' AND "+
likely[1]+"='Likely' AND "+
likely[2]+"='Likely' AND "
Now i formulate sql query as
sql ="SELECT * FROM PUNE WHERE"+temp+"Arts_And_Museum='Yes'";
But during the
ps = con.prepareStatement(sql);
this statement is compiled like
SELECT * FROM PUNE
WHERE [+likely[0]+]='Likely'
AND [+likely[1]+]='Likely'
AND [+likely[2]+]='Likely' AND Arts_And_Museum='Yes'
After deep investigation ,I came to conclusion that it interprets \" as [ or ] alternately..
As a result i get an error
How should i solve this problem?
I run a for loop and prepare a string
I am trying to write a sql syntax
This is why you should use parameterized inputs when dealing with SQL queries.
// conn refers to your database connection
PreparedStatement stmnt = null;
ResultSet rs = null;
try {
stmnt = conn.prepareStatement("SELECT * FROM tbl WHERE col > '?'");
stmnt.setInt(1, 300); //set first parameter to 300
rs = stmnt.executeQuery();
} catch(Exception ex) {
System.err.println("Database exception: " + ex.getMessage());
}
\ is a reserved character. If you want to output a quote in your string you use \".
So, this code:
temp1="\"+likely["+k+"]+\"='Likely' AND ";
Will return this string:
"+likely1]+"='Likely' AND
It seems that your sql is transforming " into [ or ]
The symbol \ is used for escaping. On doing this, you are escaping all the front characters.
Whenever you are asking for an item in array you can access it using likely[k] no need for likey["k"]
Here is how you should do it.
temp1="\\"+likely[k]+"\\='Likely' AND ";
Just change this line:
temp1="\"+likely["+k+"]+\"='Likely' AND ";
To this one:
temp1="\"" + likely[k] + "\"='Likely' AND ";

Categories