I am trying to read a temporary variable created from my MySql query as follows:
String name = "";
selectQuery = "select (select "
+ "CONCAT(s.firstname,\" \",s.surname) "
+ "AS name) "
+ "from student s, marks m where m.grade = 'fail'";
try{
pstmt = con.prepareStatement(selectQuery);
rs = pstmt.executeQuery(selectQuery);
int count = 0;
while(rs.next()){
name = rs.getString("name");
System.out.println(++count+". "+name);
}
rs.close();
pstmt.close();
}catch(Exception e){
e.printStackTrace();
}
I get SQLException as column 'name' not found. When I run the query in MySql server it runs fine.
In order for the alias to apply, it must be places outside the nested query's parenthesis, not inside it. However, you could just drop it altogether and just use the concat call directly in the select list.
Two more side notes:
Implicit joins (i.e., placing more than one table in the from list) have been deprecated for quite a while. It's considered a better practice to use explicit joins.
Regardless of the joining syntax you're using, you're missing the join condition.
Using concat_ws instead of concat may save you some hassle with handling the white space yourself.
To make a long story short:
select CONCAT_WS(' ', s.firstname, s.surname) AS name
FROM student s
JOIN marks m ON s.id = m.student_id
WHERE m.grade = 'fail'
Related
This is my database:
dragons
id, key, name, age, creation_date
users
id, name, user, pass
users_dragons
user_id, dragon_id
So this is my code for deleting dragons from the database that have a bigger key that the passed and belongs to a determination user. The SQL query works perfectly for deleting them but not for returning the array of keys from the deleted elements.
I tried using PreparedStatement but later I checked, as far as I know, that this class doesn't return arrays, and the CallableStatement is only for executing processes in the db, and I don't know how they return arrays.
String query = "" +
"DELETE FROM dragons " +
"WHERE id IN (SELECT d.id FROM dragons d, users u, users_dragons ud" +
" WHERE d.key > ?" +
" AND ud.dragon_id = d.iD" +
" AND ud.user_id in (select id from users where id = ?)) RETURNING key INTO ?";
CallableStatement callableStatement = connection.prepareCall(query);
int pointer = 0;
callableStatement.setInt(++pointer, key);
callableStatement.setInt(++pointer, credentials.id);
callableStatement.registerOutParameter(++pointer, Types.INTEGER);
callableStatement.executeUpdate();
return (int []) callableStatement.getArray(1).getArray();
The code is giving me the error, but is obvious because the CallableStatement needs a postgres function to run and not a simple SQL query
org.postgresql.util.PSQLException: This statement does not declare an OUT parameter.
Use { ?= call ... } to declare one.
at org.postgresql.jdbc.PgCallableStatement.registerOutParameter
.......
It would be really helpful how would be the correct JDBC algorithm to delete the elements from the database and return the array of keys of the deleted items.
You treat such a statement like a normal SELECT statement: use java.sql.PreparedStatement.executeQuery() or java.sql.Statement.executeQuery(String sql) to execute the statement and get a result set.
java.sql.CallableStatement is for calling Procedures (but you don't need it in PostgreSQL).
I am having code something like this.
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
Calculation of fullTableName is something like:
public String getFullTableName(final String table) {
if (this.schemaDB != null) {
return this.schemaDB + "." + table;
}
return table;
}
Here schemaDB is the name of the environment(which can be changed over time) and table is the table name(which will be fixed).
Value for schemaDB is coming from an XML file which makes the query vulnerable to SQL injection.
Query: I am not sure how the table name can be used as a prepared statement(like the name used in this example), which is the 100% security measure against SQL injection.
Could anyone please suggest me, what could be the possible approach to deal with this?
Note: We can be migrated to DB2 in future so the solution should compatible with both Oracle and DB2(and if possible database independent).
JDBC, sort of unfortunately, does not allow you to make the table name a bound variable inside statements. (It has its reasons for this).
So you can not write, or achieve this kind of functionnality :
connection.prepareStatement("SELECT * FROM ? where id=?", "TUSERS", 123);
And have TUSER be bound to the table name of the statement.
Therefore, your only safe way forward is to validate the user input. The safest way, though, is not to validate it and allow user-input go through the DB, because from a security point of view, you can always count on a user being smarter than your validation.
Never trust a dynamic, user generated String, concatenated inside your statement.
So what is a safe validation pattern ?
Pattern 1 : prebuild safe queries
1) Create all your valid statements once and for all, in code.
Map<String, String> statementByTableName = new HashMap<>();
statementByTableName.put("table_1", "DELETE FROM table_1 where name= ?");
statementByTableName.put("table_2", "DELETE FROM table_2 where name= ?");
If need be, this creation itself can be made dynamic, with a select * from ALL_TABLES; statement. ALL_TABLES will return all the tables your SQL user has access to, and you can also get the table name, and schema name from this.
2) Select the statement inside the map
String unsafeUserContent = ...
String safeStatement = statementByTableName.get(usafeUserContent);
conn.prepareStatement(safeStatement, name);
See how the unsafeUserContent variable never reaches the DB.
3) Make some kind of policy, or unit test, that checks that all you statementByTableName are valid against your schemas for future evolutions of it, and that no table is missing.
Pattern 2 : double check
You can 1) validate that the user input is indeed a table name, using an injection free query (I'm typing pseudo sql code here, you'd have to adapt it to make it work cause I have no Oracle instance to actually check it works) :
select * FROM
(select schema_name || '.' || table_name as fullName FROM all_tables)
WHERE fullName = ?
And bind your fullName as a prepared statement variable here. If you have a result, then it is a valid table name. Then you can use this result to build a safe query.
Pattern 3
It's sort of a mix between 1 and 2.
You create a table that is named, e.g., "TABLES_ALLOWED_FOR_DELETION", and you statically populate it with all tables that are fit for deletion.
Then you make your validation step be
conn.prepareStatement(SELECT safe_table_name FROM TABLES_ALLOWED_FOR_DELETION WHERE table_name = ?", unsafeDynamicString);
If this has a result, then you execute the safe_table_name. For extra safety, this table should not be writable by the standard application user.
I somehow feel the first pattern is better.
You can avoid attack by checking your table name using regular expression:
if (fullTableName.matches("[_a-zA-Z0-9\\.]+")) {
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
}
It's impossible to inject SQL using such a restricted set of characters.
Also, we can escape any quotes from table name, and safely add it to our query:
fullTableName = StringEscapeUtils.escapeSql(fullTableName);
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
StringEscapeUtils comes with Apache's commons-lang library.
I think that the best approach is to create a set of possible table names and check for existance in this set before creating query.
Set<String> validTables=.... // prepare this set yourself
if(validTables.contains(fullTableName))
{
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
//and so on
}else{
// ooooh you nasty haker!
}
create table MYTAB(n number);
insert into MYTAB values(10);
commit;
select * from mytab;
N
10
create table TABS2DEL(tname varchar2(32));
insert into TABS2DEL values('MYTAB');
commit;
select * from TABS2DEL;
TNAME
MYTAB
create or replace procedure deltab(v in varchar2)
is
LvSQL varchar2(32767);
LvChk number;
begin
LvChk := 0;
begin
select count(1)
into LvChk
from TABS2DEL
where tname = v;
if LvChk = 0 then
raise_application_error(-20001, 'Input table name '||v||' is not a valid table name');
end if;
exception when others
then raise;
end;
LvSQL := 'delete from '||v||' where n = 10';
execute immediate LvSQL;
commit;
end deltab;
begin
deltab('MYTAB');
end;
select * from mytab;
no rows found
begin
deltab('InvalidTableName');
end;
ORA-20001: Input table name InvalidTableName is not a valid table name ORA-06512: at "SQL_PHOYNSAMOMWLFRCCFWUMTBQWC.DELTAB", line 21
ORA-06512: at "SQL_PHOYNSAMOMWLFRCCFWUMTBQWC.DELTAB", line 16
ORA-06512: at line 2
ORA-06512: at "SYS.DBMS_SQL", line 1721
I have a java class that is supposed to display a table. So i want to search FROM table called Film the filmtitle and the film genre but the OR query doesn't work? any idea how to fix this?
heres my code btw
public void searchbyTitle()
{
String sql = "SELECT filmtitle, filmyear, filmgenre, companyname FROM production, film,
company WHERE LOWER(filmtitle) like LOWER
(?) OR LOWER(filmgenre) like LOWER (?) and production.companyid = company.companyid AND production.filmid = film.filmid";
con = DBConnect.getConnection();
try
{
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, "%" +txtSearch.getText()+"%");
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(SQLException e)
{
e.printStackTrace();
}
}
it only works if i remove the or,but i also want to be able to search for film genre
LOWER is also what i used so that it will be case insensitive also used postgresql..any help is appreciated
The logic is doing exactly what you are telling MySQL to do. It is just not what you intend.
If you are having trouble with conditional expressions, then use parentheses to explicitly do what you want:
WHERE (LOWER(filmtitle) like LOWER (?) OR
LOWER(filmgenre) like LOWER (?)
) and
production.companyid = company.companyid AND production.filmid = film.filmid;
Ouch! I notice that you have commas in the FROM clause. If you had used explicit JOIN syntax, your query would have been correct to begin with. The correct way to write the query is:
SELECT filmtitle, filmyear, filmgenre, companyname
FROM production p JOIN
film f
ON p.filmid = f.filmid JOIN
company c
ON p.companyid = c.companyid
WHERE LOWER(filmtitle) like LOWER(?) OR LOWER(filmgenre) like LOWER(?);
Notice the parentheses are no longer needed in the WHERE, because there is no AND competing with the OR.
Simple rule: Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. It would have saved you a lot of time today.
I am doing a join to retrieve data from a database and am assigning it to variables
rs = select.executeQuery("SELECT PK_Task, PointPerson, Task.ScrumId, Story.ScrumId, Product.ScrumId FROM [Task] " +
"INNER JOIN [Story] ON StoryId=PK_Story INNER JOIN [Product] ON ProductId=PK_Product WHERE Product.Deleted!=1");
To retrieve this data:
while(rs.next()) {
String taskId = rs.getString("PK_Task");
}
But how to I get data from the columns that have the same name on different tables:
while(rs.next()) {
Long taskScrumId = rs.getLong("Task.ScrumId");
}
Results in:
com.microsoft.sqlserver.jdbc.SQLServerException: The column name Task.ScrumId is not valid.
Either use getString(int) or use Task.ScrumID as task_scrum_id and getString("task_scrum_id"). I personally prefer the latter approach.
So, in this case, the task would be
String taskId = rs.getString(3)
or your query would be
select.executeQuery("SELECT PK_Task, PointPerson, Task.ScrumId as task_scrum_id, ...
String taskId = rs.getString("task_scrum_id")
You can give the columns aliases.
Please take a look at the below example.
SELECT
TeacherName = T.Name
, StudentName = S.Name
FROM Teachers T
JOIN Students S ON T.SomeValue = S.SomeValues
I have this piece of code, with a prepared statement. I know the query is redundant. the parameter id is a string <space>413530 (" 413530"). Please note the preceding whitespace character.
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=?";
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
newPrepStatement.setString(1, id);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I do not get any results after executing this query.
Now, if I use the same statements and append the parameter as part of the string as follows:
String query = "SELECT RSCode as id FROM Customer WHERE RSCode=" + id;
PreparedStatement newPrepStatement = connection
.prepareStatement(query);
resultSet1 = newPrepStatement.executeQuery();
while (resultSet1.next()) {
System.out.println("Got a result set.");
logindata.add(resultSet1.getString("id"));
}
I get a result as after executing this prepared statement. Same also works with a java.sql.statement
I wish to know why the driver ignores the whitespace in the second piece of code, but has a problem in the first part.
If you use setString the parameter will be bound as a string resulting in this SQL (considering the bound parameter an SQL string):
SELECT RSCode as id FROM Customer WHERE RSCode=' 0123';
If you use concatenation the SQL used will be (considering the concatenated value as an integer, since space will be ignored as part of the SQL syntax):
SELECT RSCode as id FROM Customer WHERE RSCode=<space>0123;
In this case I would advise to convert it to int or long or whatever it is and bind it with the right type. With setInt() or setLong().
And if you field is a string you could normalize it first using for example:
String normalizedValue = String.trim(value);
newPrepStatement.setString(1, normalizedValue);
or even direct in SQL like:
SELECT RSCode as id FROM Customer WHERE RSCode=TRIM(?);
In scenario - 1, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode=' 413530'"
In scenario - 2, the query will look like this
"SELECT RSCode as id FROM Customer WHERE RSCode= 413530"