Executing multi - statement query in one session - java

I have asked this question and wanted to edit it , however StackOverflow for some reason did not allow me to edit . So here is the edited version
For example a query :
create volatile table testTable as (select * from ... blah blah) ;
select top 10 * from testTable ;
drop table testTable ;
It executes perfect in sql assistance as one session. I am sure it is possible to execute it in Java in one session.
Goal : need to execute it in one session similar to sql assistant so that it is possible to refer to the volatile table in the subsequent select statement. Also the data from the select statement should be saved in the ResultSet
PS
I saw one answer to a similar question about mysql. The trick is to turn on allow multiple queries
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
For teradata specifically,
what is the solution ?
I tried
String dbUrl = "jdbc:odbc:dsn?allowMultiQueries=true";

What is exactly failing?
Is there an error message "testtable doesn't exist"? Then your program closes the connection after each request.
Is the table empty when you do the SELECT? Then you forgot to add ON COMMIT PRESERVE ROWS to the CREATE.

Related

SQL Injection modify table

I am doing an exercise in class to find web page vulnerabilities through a user/password form and we are suppouse to be able to modify columns of a table using SQL injection.
I know the tables of the database, for instance I am trying to modify the table users that has the colums id, password and email.
The problem is that for INSERT, UPDATE or DELETE the server code use the executeUpdate() method and for SELECT use the executeQuery() method which returns the ResultSet, so obviusly when I try someting like:
correctpassword'; UPDATE usuarios SET id='newname' WHERE id='oldname'; --
it returns an error because UPDATE does not return the ResultSet object.
I have also tried nested queries so the main consult would be a SELECT so it would actually return a ResultSet object but it doesnt work either. The query is:
correctpassword'; SELECT id FROM usuarios WHERE id = (SELECT id FROM usuarios WHERE id=?admin?; UPDATE usuarios SET id=?luciareina? WHERE id=?admin?); --
Do you know anyway to do this? Thank you very much in advance!
Depending on the database server you have, you can not have an update statement inside of a select statement.
you should close out the existing query and then do the update
Also, make sure the column you are updating is not an auto generated/key column that is not updatable.
SELECT id FROM usuarios WHERE id = 1; UPDATE usuarios SET id=1 WHERE id=2
You should test your injection directly on server to see if it is valid before testing it via the webpage.

InvalidQueryException despite of correct query

I am using SpringBoot connceted with Hibernate and Cassandra Database. I made couple of methods using ResultSet and everything works perfect till now. I create another method, create query and then ResultSet.
String queryString = query.toString().replace("?", dayList.toString());
ResultSet rS = dataSource.executeQuery(queryString);
It throws me:
com.datastax.driver.core.exceptions.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename
Query is correct. When I execute query in database it returns me proper data.
It is wierd because I use same implementation in previous method and it works.
Here is my query:
SELECT * FROM object_action_statistics WHERE day IN ('2018-04-29','2018-04-30') AND action_id=14 AND timestamp_from>=1525099500073 AND timestamp_from<1525120897000 ALLOW FILTERING
Correct query should be like this:
SELECT * FROM KEYSPACE_NAME.object_action_statistics WHERE day IN ('2018-04-29','2018-04-30') AND action_id=14 AND timestamp_from>=1525099500073 AND timestamp_from<1525120897000 ALLOW FILTERING
I guess you forgot to put keyspace name ahead of table name.

Updating two sql tables using one query in java

I want to update two sql tables at once in java. I'm using SQLiteManager. Could someone please suggest a way of doing that?
Assuming you have the driver and connection to the database, you should be able to run most sql commands from java. There is not a single sql statement that will update two tables at once but you can update each table in turn which will have the same effect.
See http://www.javaworkspace.com/connectdatabase/connectSQLite.do for some examples.
For a table update, use
statement.execute(sql);
where sql is a string of the form
sql = "UPDATE myTable SET myColumn = newValue WHERE someOtherColumn=value";

Checking if table exist or not

I am retrieving data from database using jdbc. In my code I am using 3-4 tables to get data. But sometimes if table is not present in database my code gives exception. How to handle this situation. I want my code to continue working for other tables even if one table is not present. Please help.
I have wrote a code like this
sql="select * from table"
now Result set and all.
If table is not present in database it give exception that no such table. I want to handle it. In this code I cannot take tables which are already present in advance . I want to check here itself if table is there or not.
Please do not mark it as a duplicate question. The link you shared doesnot give me required answer as in that question they are executing queries in database not through JDBC code
For Sybase ASE the easiest/quickest method would consist of querying the sysobjects table in the database where you expect the (user-defined) table to reside:
select 1 from sysobjects where name = 'table-name' and type = 'U'
if a record is returned => table exists
if no record is returned => table does not exist
How you use the (above) query is up to you ...
return a 0/1-row result set to your client
assign a value to a #variable
place in a if [not] exists(...) construct
use in a case statement
If you know for a fact that there won't be any other object types (eg, proc, trigger, view, UDF) in the database with the name in question then you could also use the object_id() function, eg:
select object_id('table-name')
if you receive a number => the object exists
if you receive a NULL => the object does not exist
While object_id() will obtain an object's id from the sysobjects table, it does not check for the object type, eg, the (above) query will return a number if there's a stored proc named 'table-name'.
As with the select/sysobjects query, how you use the function call in your code is up to you (eg, result set, populate #variable, if [not] exists() construct, case statement).
So, addressing the additional details provided in the comments ...
Assuming you're submitting a single batch that needs to determine table existence prior to running the desired query(s):
-- if table exists, run query(s); obviously if table does not exist then query(s) is not run
if exists(select 1 from sysobjects where name = 'table-name' and type = 'U')
begin
execute("select * from table-name")
end
execute() is required to keep the optimizer from generating an error that the table does not exist, ie, the query is not parsed/compiled unless the execute() is actually invoked
If your application can be written to use multiple batches, something like the following should also work:
# application specific code; I don't work with java but the gist of the operation would be ...
run-query-in-db("select 1 from sysobjects where name = 'table-name' and type = 'U'")
if-query-returns-a-row
then
run-query-in-db("select * from table-name")
fi
This is the way of checking if the table exists and drop it:
IF EXISTS (
SELECT 1
FROM sysobjects
WHERE name = 'a_table'
AND type = 'U'
)
DROP TABLE a_table
GO
And this is how to check if a table exists and create it.
IF NOT EXISTS (
SELECT 1
FROM sysobjects
WHERE name = 'a_table'
AND type = 'U'
)
EXECUTE("CREATE TABLE a_table (
col1 int not null,
col2 int null
)")
GO
(They are different because in table-drop a temporary table gets created, so if you try to create a new one you will get an exception that it already exists)
Before running the query which has some risk in table not existing, run the following sql query and check if the number of results is >= 1. if it is >= 1 then you are safe to execute the normal query. otherwise, do something to handle this situation.
SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')
I am no expert in Sybase but take a look at this,
exec sp_tables '%', '%', 'master', "'TABLE'"
Sybase Admin

Why does my code produce the error: The statement did not return a result set [duplicate]

This question already has answers here:
Execute "sp_msforeachdb" in a Java application
(3 answers)
Closed 1 year ago.
I am executing the following query from Microsoft SQL Server Studio, which works fine and displays results:
SELECT *
INTO #temp_table
FROM md_criteria_join
WHERE user_name = 'tecgaw'
UPDATE #temp_table
SET user_name = 'tec'
WHERE user_name != 'tec'
SELECT *
FROM md_criteria_join
WHERE user_name = 'tec'
AND view_name NOT IN (SELECT view_name
FROM md_criteria_join
WHERE user_name = 'tecgaw')
UNION
SELECT *
FROM #temp_table
ORDER BY view_name,
user_name,
crit_usage_seq,
crit_join_seq
However, if I execute the same query in Java, an Exception is thrown stating
The statement did not return a result set.
Here's the Java code:
statement = conn.getConnection().createStatement();
resultSet = stmt.executeQuery(sql.toString());
Is that because I cannot do multiple SQL queries in one statement (I.e., Creating the #temp_table, updating it, and then using for it my select statement)?
JDBC is getting confused by row counts.
You need to use SET NOCOUNT ON.
Use execute statement for data manipulation like insert, update and delete and
executeQuery for data retrieval like select
I suggest you to separate your program into two statements one execute and one executeQuery.
If you do not wish to do that, try separating the statements with semi-colon. But I am not sure about this action if this gives you a resultset or not.
I have found similar question in StackOverflow here. You should enable connection to support multiple statements and separate them using ;. For concrete examples see that answer. However it is for MySql only.
Also I think you can rewrite your SQL into single query
SELECT columnA, columnB, 'tec' as user_name from md_criteria_join
WHERE (
user_name = 'tec'
AND view_name NOT IN (
SELECT view_name
FROM md_criteria_join
WHERE user_name = 'tecgaw')
)
OR user_name = 'tecgaw'
ORDER BY view_name, user_name, crit_usage_seq, crit_join_seq
Another option is to move your statements to stored procedure and ivoke it from JDBC using CallableStatement
Or maybe you should try executing it with multiple jdbc statements like this
Connection conn = conn.getConnection(); //just to make sure its on single connection
conn.createStatement("SELECT INTO #temp_table").executeUpdate();
conn.createStatement("UPDATE #temp_table").executeUpdate();
conn.createStatement("SELECT ...").executeQuery();
Note you have to close resources and maybe for better performance you could use addBatch and executeBatch methods
in ms sql you also have to do set nocount on right at the beginning of the stored procedure along with terminating select / update/ insert block statement with ";"

Categories