I run my program, the database is connected to and then it gives me two errors. One saying
'Schema "ROOT" does not exist'
and another saying
'Lexical error at line 1, column 8. Encountered: "#"(64), after:"".
Here is the code from the two SQL statements:
private void UpdateJTable() {
String sql ="select idhonscores AS RowNo , Name, Characters, Kills, Deaths, Assists, XPM, CK from honscores";
try {
st = conn.prepareStatement(sql);
rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
That is from the first error and
String sql3 ="SELECT "+"#rn:=#rn+1"+" AS Rank, Name, Kills
FROM (Select Name, sum(Kills) as Kills
from honscores group by Name order by Kills DESC) t1,
(SELECT "+"#rn:=0"+") t2;";
Is for the second error
In derby the default schema is always the schema of the user you use to create the jdbc connection. I can't tell from you question, how you initialize and setup the derby database. But appending ;create=true to the jdbc-url might help (this will create the db and schema if it does not exist).
You can change to a different schema by executing:
SET SCHEMA MYSCHEMA;
The #-syntax might not be available in derby. Not everything that works in another db (especially if it is db specific) will work in derby.
What has been said about username being the default schema is true. If you do not specify a username the default schema will be APP. This schema always exists. If you connect as user root the schema "root" will not be created until you create a table in it. E.g:
ij> connect 'jdbc:derby:memory:foo;user=root;create=true';
ij> show schemas;
TABLE_SCHEM
------------------------------
APP
NULLID
SQLJ
SYS
SYSCAT
SYSCS_DIAG
SYSCS_UTIL
SYSFUN
SYSIBM
SYSPROC
SYSSTAT
11 rows selected
ij> create table foo(i int) ;
0 rows inserted/updated/deleted
ij> show schemas;
TABLE_SCHEM
------------------------------
APP
NULLID
ROOT
SQLJ
SYS
SYSCAT
SYSCS_DIAG
SYSCS_UTIL
SYSFUN
SYSIBM
SYSPROC
SYSSTAT
12 rows selected
Wrt. # in table and column names: That is only allowed if you quote the name containing #. E.g.:
ij> create table #T#(#c# int);
ERROR 42X02: Lexical error at line 1, column 14. Encountered: "#" (64), after : "".
ij> create table "#T#"("#c#" int);
0 rows inserted/updated/deleted
ij> insert into "#T#" values (0),(1),(2);
3 rows inserted/updated/deleted
ij> select * from "#T#";
#c#
-----------
0
1
2
3 rows selected
Note however, that when quoting a name it becomes case-sensitive. So in the previous example the following fails:
ij> select * from "#t#";
ERROR 42X05: Table/View '#t#' does not exist.
because in quotes, #T# and #t# are considered different names.
Related
I have a script, which I run successfully in postgres db, however it was failed when I run in hsqldb.
Can someone help me change this sql to make it work for both HSQLDB and Postgres DB?
Below is my script:
UPDATE tableA af
SET columnA2 = b.columnB2
from
( select columnB1, columnB2 from.....) as b
Where af.columnA1 = b.columnB1;
This throws the following exception when I run it in hsqldb:
Caused by: java.sql.SQLSyntaxErrorException: user lacks privilege or
object not found: b.columnB2 Caused by: org.hsqldb.HsqlException: user
lacks privilege or object not found: b.columnB2
Thanks.
Updated:
I created another view to make my question more clear.
table_A has 2 columns: company_code, company_number
and view_B has 2 columns: company_code, company_number_correct_answer
table_A has 10000 rows, and view_B has only 2 rows.
What I want is updating 2 record in table_A, with company_code existing in view_B and set table_A.company_number = view_B.company_number_correct_answer
In standard SQL, the FROM clause (or JOIN or similar things) is not valid for the UPDATE statement.
If you want an UPDATE statement that works across multiple database products, you will have to use a co-related sub-query:
update table_a
set columna2 = (select columnb2
from table_b
where table_b.columnb1 = table_a.columna1)
where exists (select *
from table_b
where table_b.columnb1 = table_a.columna1);
Note that this requires that table_b.columnb1 is a unique or primary key, otherwise the sub-query would return more than one row which will lead to an error).
You can also use MERGE in HSQLDB
MERGE INTO tableA af
USING (select columnB1, columnB2 from.....) as b
ON af.columnA1 = b.columnB1
WHEN MATCHED THEN
UPDATE SET af.columnA2 = b.columnB2
I have a query which I am trying to test. The query should update the data if it finds data in the table with existing primary key. If it doesn't then insert into the table.
The Primary key is of type int and in the properties I can see Identity is set to "True" which I assume it means that it will automatically set the new id for the primary if it is inserted.
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia FROM Test_table) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
The issue here is this query doesn't work and it never inserts the data or updates. Also, query gets compiled and I don't get any compilation error
Also the reason I want this query is to work because then I will use Java prepared statement to query the database so I am assuming I can do
SELECT ? ID,? Fascia FROM Test_table
So that I can pass the values with set methods in java.
Please let me know if there is something wrong in my query.
You are selecting from the target table as your source.
You either need to remove your FROM Test_table or have at least 1 row in Test_table prior to your merge.
rextester demo: http://rextester.com/XROJD28508
MERGE INTO Test_table t
USING (SELECT 461232 ID,'Test1-data' Fascia --FROM Test_table
) s
ON (t.ID = s.ID)
WHEN MATCHED THEN
UPDATE SET t.Fascia = s.Fascia
WHEN NOT MATCHED THEN
INSERT (Fascia)
VALUES (s.Fascia);
Hello guys I need fill a table with el result of my query like....
SELECT FIELD1, FIELD2, X FROM OLDTABLE WHERE X=Y
I am a Java developer, my friends, RPG developers in the AS400. When they execute a a Query have a option to save the query result in a file
The option is called SELECT output and can choice 1 Display 2 Printer 3 File
Can do this directly from a query? or is a native iSeries option ?
Create a table with iseries sql
create a table with data.
create table abc as (select x,y,z from sometable where x=y) with data
create an empty table.
create table abc as (select x,y,z from sometable where x=y) data definition only
There is no output to printer using just sql.
Query will prompt you to replace an existing table. Straight SQL won't prompt to replace an existing table so you have two scenarios (see note) .
If the output table doesn't exist, all you need is
create table newtable as (select <...> from oldtable) with data
If the output table already exists, all you need is an insert with sub-select.
Insert into newtable
Select <...> from oldtable
NOTE
With the release of TR10 for v7.1 and TR2 for v7.2 in May 2015, IBM has added support the OR REPLACE clause to the CREATE TABLE statement. So if you happen to be on those TRs or higher, you could simply use:
create or replace table newtable as (select <...> from oldtable) with data
Could compile the SQL into a query manager query (CRTQMQRY) then run the query via (STRQMQRY).
To do that, put the query into the some sort of source file with a member type of TXT. Get to a command line and run the CRTQMQRY command and create the output QMQRY. STRQMQRY can be prompted and you can save the results in either an output file or a printout or look at it interactively. If you submit it as a batch job, viewing the output interactively won't work too well.
The problem is following
By executing the below queries in SQL Plus, everything is working perfect:
column firstname new_value v_firstname
select firstname from tbcustomer where customer_id = 111
select '&v_firstname', wrk.* from tbwork where customer_id = 111
But when when i tried to execute these queries from Java program, i get java.sql.SQLException: ORA-00900: invalid SQL statement on the first SQL query
Connection connection = null;
Statement stat = null;
String query = "column due_date new_value v_due_date";
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection = DriverManager.getConnection(url, username, password);
stat = connection.createStatement();
boolean res_num = stat.execute(query);
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
e.printStackTrace();
}
Now the question is how to overcome this error and execute first query or do you have any other solution to define variable on the oracle session and use it in other SQL statements.
For instance third query is one of the many queries that i need to execute and all of them will have same first name field
column is a SQL*Plus command. It is not valid in SQL or PL/SQL so you cannot use it in a Java application.
Substitution variables like &v_firstname are also a SQL*Plus construct-- they are not valid in SQL or PL/SQL so you cannot use them in a Java application.
If your goal is to get the firstname from tbcustomer and all the columns from tbwork in a single query, you would need to join the two tables. Assuming that both tables have a customer_id column and that is how the two tables are supposed to be joined
SELECT cust.firstname,
work.*
FROM tbcustomer cust
JOIN tbwork work ON (cust.customer_id = work.customer_id)
WHERE cust.customer_id = 111
Assuming that you will be executing this query for multiple customer_id values, however, 111 should be a bind variable instead of a literal and your Java code should be using a PreparedStatement to prepare the SQL statement, then binding a value like 111 using the setInt method before executing the query.
If you want to break this into two database calls, you can simply do something like
PreparedStatement stmtGetFirstName = connection.prepareStatement("select firstname from tbcustomer where customer_id = ?");
stmtGetFirstName.setInt( 1, 111 );
ResultSet rsGetFirstName = stmtGetFirstName.executeQuery();
String firstName = rsGetFirstName.getString();
PreparedStatement stmtGetWork = connection.prepareStatement("select ?, work.* from tbwork where customer_id = ?");
stmtGetWork.setString( 1, firstName );
stmtGetWork.setInt( 2, 111 );
ResultSet rsGetWork = stmtGetWork.executeQuery();
If you can guarantee that all 600 million executions will occur in the same database session, you could use a database context. You would need to create the context and the package it uses in the database
SQL> create or replace context fname_ctx using scott.pkg_get_fname;
Context created.
SQL> ed
Wrote file afiedt.buf
1 create or replace package pkg_get_fname
2 is
3 procedure set_fname( p_customer_id in number );
4 function get_fname return varchar2;
5* end;
SQL> /
Package created.
SQL> create or replace package body pkg_get_fname
2 is
3 procedure set_fname( p_customer_id in number )
4 as
5 begin
-- Obviously, you'd get the data here from your table rather than hard-coding 'Bob'
6 dbms_session.set_context( 'fname_ctx', 'fname', 'Bob' );
7 end;
8
9 function get_fname
10 return varchar2
11 is
12 l_fname varchar2(100);
13 begin
14 l_fname := sys_context( 'fname_ctx', 'fname' );
15 return l_fname;
16 end;
17 end;
18 /
Package body created.
From Java, you could then call pkg_get_fname.set_fname(111) to set the context and use the function pkg_get_fname.get_fname in your query.
It seems odd, however, to be concerned about performance and to be planning to execute 600 million queries from Java against the database. That's going to involve a ton of round-trips over the network between the middle tier and the database server-- if you're really concerned about performance, you'd push that work to stored procedures in the database to eliminate the network round-trips. And the fact that you're executing them so many times makes me suspect that you're doing a lot of row-by-row processing rather than letting the database do set-based operations. That's also going to be a major source of poor performance. Plus, databases are born to join, so it's pretty unusual for a simple join like this to add appreciably to the cost of a query assuming that proper indexes are in place.
i am using sql server 2005 and jdbc. Trying to insert values in to table ContentModification with below code
java.sql.Date date= new java.sql.Date(Calendar.getInstance().getTimeInMillis());
sql = "insert into ContentModification values(?,?)";
pc.setString(1, space);
pc.setDate(2, date); // line 3
pc.executeUpdate();//line 4
At line 3 i am getting error com.jnetdirect.jsql.JSQLException: Invalid parameter index:2 Valid range is 1 to 1
i am not getting whats the reason for this?
My create table script is below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ContentModification](
[XWC_NAME] [varchar](255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[XWC_LASTUPDATE] [datetime] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
Using JSQLConnect(5.95) Trial license, jdk 1.6 and SQL Express 2008 your code executes successfully. This exception generally occurs when you have miss-match between the number of '?' marks in PreparedStatement and the index of setDate() / setString()
You might try changing this line :
sql = "insert into ContentModification(XWC_NAME, XWC_LASTUPDATE) values(?,?)";