How to dynamically execute sql statement - sql

I want to execute an sql statement dynamically based on the column passed by user through jTextField.
str=select "+jTextField.getText()+" from table ;
This statement works fine of the column name does not have a space.
Example : suppose I have two columns = Priority and Request Type.
This above statement works perfect if I type priority but fails when I use request type
and
if I use the statement
str=select ["+jTextField.getText()+"] from table ;
then Request Type entry will work fine but Priority won't.
Any idea to resolve this issue.

You may need to trim trailing/leading spaces from the field name, otherwise it should work fine:
str=select ["+jTextField.getText().trim()+"] from table ;
Are you sure Priority is the right field name within that table?
Also be aware that you are vulnerable to SQL injection. Suppose you put the following in jTextField:
"null] FROM table; DROP TABLE table; --"
Then the result is
select [null] FROM table; DROP TABLE table; --] from table ;

Related

How can you filter Snowflake EXPLAIN AS TABULAR syntax when its embedded in the TABLE function? Can you filter it with anything?

I have a table named Posts I would like to count and profile in Snowflake using the current Snowsight UI.
When I return the results via EXPLAIN using TABLULAR I am able to return the set with the combination of TABLE, RESULT_SCAN, and LAST_QUERY_ID functions, but any predicate or filter or column reference seems to fail.
Is there a valid way to do this in Snowflake with the TABLE function or is there another way to query the output of the EXPLAIN using TABLULAR?
-- Works
EXPLAIN using TABULAR SELECT COUNT(*) from Posts;
-- Works
SELECT t.* FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) as t;
-- Does not work
SELECT t.* FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())) as t where operation = 'GlobalStats';
-- invalid identifier 'OPERATION', the column does not seem recognized.
Tried the third example and expected the predicate to apply to the function output. I don't understand why the filter works on some TABLE() results and not others.
You need to double quote the column name
where "operation"=
From the Documentation
Note that because the output column names from the DESC USER command
were generated in lowercase, the commands use delimited identifier
notation (double quotes) around the column names in the query to
ensure that the column names in the query match the column names in
the output that was scanned

Derby run sql script by redirecting standardIO

I have the following join.sql script:
connect 'jdbc:derby:barra';
show tables;
create table sp500_univ as
select a.*,b.* from (select * from LEFT_SIDE) as a
left join (select * from RIGHT_SIDE) as b
on a.cmp_flg = b.cmp_flg2;
disconnect;
exit;
which I run with the following command:
java org.apache.derby.tools.ij < join.sql
and get the following output:
java org.apache.derby.tools.ij < join.sql
ij version 10.14
ij> ij> TABLE_SCHEM |TABLE_NAME |REMARKS
------------------------------------------------------------------------
APP |LEFT_SIDE |
APP |RIGHT_SIDE |
2 rows selected
ij> > > > ERROR 42X01: Syntax error: Encountered "<EOF>" at line 4, column 25.
Issue the 'help' command for general information on IJ command syntax.
Any unrecognized commands are treated as potential SQL commands and executed directly.
Consult your DBMS server reference documentation for details of the SQL syntax supported by your server.
ij> ij>
If I run this sql right from the command line in IJ it works.
apparently when running from a file you can't create tables and load data from a select statement. You need to add the WITH NO DATA. The WITH DATA option has not yet been implemented. From Derby's documentation:
CREATE TABLE ... AS ...
With the alternate form of the CREATE TABLE statement, the column names and/or the
column data types can be specified by providing a query. The columns in the query
result are used as a model for creating the columns in the new table.
If no column names are specified for the new table, then all the columns in the
result of the query expression are used to create same-named columns in the new
table, of the corresponding data type(s). If one or more column names are specified
for the new table, then the same number of columns must be present in the result of
the query expression; the data types of those columns are used for the corresponding
columns of the new table.
The WITH NO DATA clause specifies that the data rows which result from evaluating the
query expression are not used; only the names and data types of the columns in the
query result are used. The WITH NO DATA clause must be specified; in a future
release, Derby may be modified to allow the WITH DATA clause to be provided, which
would indicate that the results of the query expression should be inserted into the
newly-created table. In the current release, however, only the WITH NO DATA form of t
the statement is accepted.

Inserting new rows into table-1 based on constraints defined on table-2 and table-3

I want to append new rows to a table-1 d:\dl based on the equality constraint lower(rdl.subdir) = lower(tr.n1), where rdl and tr would be prospective aliases for f:\rdl and f:\tr tables respectively.
I get a function name is missing ). message when running the following command in VFP9:
INSERT INTO d:\dl SELECT * FROM f:\rdl WHERE (select LOWER(subdir)FROM f:\rdl in (select LOWER(n1) FROM f:\tr))
I am using the in syntax, instead of the alias based equality statement lower(rdl.subdir) = lower(tr.n1) because I do not know where to define aliases within this command.
In general, the best way to get something like this working is to first make the query work and give you the results you want, and then use it in INSERT.
In general, in SQL commands you assign aliases by putting them after the table name, with or without the keyword AS. In this case, you don't need aliases because the ones you want are the same as the table names and that's the default.
If what you're showing is your exact code and you're running it in VFP, the first problem is that you're missing the continuation character between lines.
You're definitely doing too much work, too. Try this:
INSERT INTO d:\dl ;
SELECT * ;
FROM f:\rdl ;
JOIN f:\tr ;
ON LOWER(rdl.subdir) = LOWER(tr.n1)

Oracle, dynamically determine column name

Suppose I have a table of custom column names that all have the pattern COL##, where ## is any integer. So a typical query would be:
select COL12 from MyCustomTable;
So in another table, I have all those integers and I'd like to create a query using the table of integers to construct a dynamic query into MyCustomTable.
Something like:
select 'COL' || (select colId from IdTable where Id = 12) from MyCustomTable;
But instead of just returning the string 'COL12' for every row, return the actual values identified by the column name COL12.
Don't worry about my overall problem :) I'm just curious to know if I can do this from a sqldeveloper window directly without writing any code/procedures/functions, etc.
An obvious and absolutely insecure way of doing this would be usage of EXECUTE IMMEDIATE statement.
Another is to use SPOOL command to output results into temporary file, then set SPOOL OFF and execute this file with # directive.

In sqlite How to add column in table if same column is not exists in table

How can I add a column in an SQLite table if and only if the same column does not exist in the table?
Using ALTER TABLE I am able to create a new column but want to know how to check whether that column already exists in the table or not?
SQLite returns an error like "no such column: foo" if the table doesn't contain the column:
select foo from yourTable limit 1
Also you can get the create-table statement:
select sql from sqlite_master where tbl_name = 'YourTableName'
and then parse the result, looking for the column-name. I don't know of an elegant way to query the list of columns for a specified table, though one may exist.
Also if you attempt to do this:
alter table YourTable add column foo {column-def whatever it is}
you get an error from SQLite if the column already exists. You could trap that error too.
Finally you could do this:
select sql from sqlite_master
where tbl_name = 'YOURTABLE' and sql like '%"foo" CHAR%'; -- or whatever type
and if the specified table contains the column which is surrounded by double-quotes in the query, and with the type you have specified, you will get a result, otherwise an empty set. Specifying the datatype ensures that your LIKE substring match occurs on a column-name.
There's no way (that I know of) to do it all in a single SQLite query. You must use application code to manage the If/Elseness.
Check if table exists or not:
select count(*) from sqlite_master where type = 'table' and name = MyTable';
Check if column exists in table or now
pragma table_info(thumbnail);
However, a better approach may be explicit database schema updates based on schema versions your application maintains (e.g. specific alter table statement to go from schema version 1 to 2):
pragma user_version;
It seems like that it is impossible to do checking if the column not exists and addindg the new column in one command, because Sqlite don't support "IF NOT EXISTS" for column. "IF NOT EXISTS" works only on table.
Here is what I will do:
rev = ExecuteStatement("SELECT columnNamexx FROM tableNamexx limit 1;");
if(rev != SQLITE_OK){ // add col to table
ExecuteStatement("ALTER TABLE tableNamexx ADD COLUMN columnNamexx INTEGER DEFAULT 0;");
}
You can view the table columns by using '.schema tableName'