Using sqlerrm in insert statement in 10g
Hi,
I do not have 10g to test the following snippet, which tries to use sqlerrm in an insert statement:
-- start testcase
drop table tbl;
drop table err;
create table tbl (x number);
create table err (a number, b varchar2(4000));
declare
n_tmp tbl.x%type;
begin
select x into n_tmp from tbl;
exception
when others then
-- the line below works in 9i
-- dbms_output.put_line('Sqlerrm: '||sqlerrm);
-- but the insert statement doesn't work in 9i, how about 10g ?
insert into err(a,b) values (1,sqlerrm);
commit;
end;
declare
n_tmp tbl.x%type;
begin
select x into n_tmp from tbl;
exception
when others then
-- the line below works in 9i
-- dbms_output.put_line('Sqlerrm: '||sqlerrm);
-- the insert statement works in 9iR2 but the error message is
-- not the one sought, how about 10g ?
insert into err(a,b) values (1,sys.standard.sqlerrm);
commit;
end;
/Can someone test it on any release/edition of 10g please ?
The tests on 9iR2 below behave predictably:
SQL>
SQL> @ver
BANNER
Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
PL/SQL Release 9.2.0.8.0 - Production
CORE 9.2.0.8.0 Production
TNS for Solaris: Version 9.2.0.8.0 - Production
NLSRTL Version 9.2.0.8.0 - Production
SQL>
SQL>
SQL> -- start testcase
SQL> drop table tbl;
Table dropped.
SQL> drop table err;
Table dropped.
SQL>
SQL> create table tbl (x number);
Table created.
SQL> create table err (a number, b varchar2(4000));
Table created.
SQL>
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception
6 when others then
7 -- the line below works in 9i
8 -- dbms_output.put_line('Sqlerrm: '||sqlerrm);
9 -- but the insert statement doesn't work in 9i, how about 10g ?
10 insert into err(a,b) values (1,sqlerrm);
11 commit;
12 end;
13 /
insert into err(a,b) values (1,sqlerrm);
ERROR at line 10:
ORA-06550: line 10, column 36:
PL/SQL: ORA-00984: column not allowed here
ORA-06550: line 10, column 5:
PL/SQL: SQL Statement ignored
SQL>
SQL> --
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception
6 when others then
7 -- the line below works in 9i
8 -- dbms_output.put_line('Sqlerrm: '||sqlerrm);
9 -- the insert statement works in 9iR2 but the error message is
10 -- not the one sought, how about 10g ?
11 insert into err(a,b) values (1,sys.standard.sqlerrm);
12 commit;
13 end;
14 /
PL/SQL procedure successfully completed.
SQL>
SQL> select * from err;
A B
1 ORA-0000: normal, successful completion
SQL>
SQL>The behavior of the second pl/sql block was mentioned by Nicolas:
Re: INSERT INTO ..VALUES (SQLERRM, SQLCODE, SYSDATE) doesn't work?
Is there any change in 10g ?
Thanks in advance,
pratz
(Sorry, the hyperlink is getting modified automatically; remove the backslash ("\") immediately before the ampersand ("&") character.)
Message was edited by:
pratz
Same in 10.2.0.3.0
SQL*Plus: Release 10.1.0.4.2 - Production on Thu Jan 24 11:55:53 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> drop table tbl;
Table dropped.
SQL>
SQL> drop table err;
Table dropped.
SQL>
SQL> create table tbl (x number);
Table created.
SQL>
SQL> create table err (a number, b varchar2(4000));
Table created.
SQL> declare
2 n_tmp tbl.x%type;
3 begin select x into n_tmp from tbl;
4 exception when others then
5 -- the line below works in 9i
6 --dbms_output.put_line('Sqlerrm: '||sqlerrm);
7 -- but the insert statement doesn't work in 9i, how about 10g ?
8 insert into err(a,b) values (1,sqlerrm);
9 commit;
10 end;
11 /
insert into err(a,b) values (1,sqlerrm);
ERROR at line 8:
ORA-06550: line 8, column 32:
PL/SQL: ORA-00984: column not allowed here
ORA-06550: line 8, column 1:
PL/SQL: SQL Statement ignored
SQL> declare
2 n_tmp tbl.x%type;
3 begin
4 select x into n_tmp from tbl;
5 exception when others then
6 -- the line below works in 9i
7 --dbms_output.put_line('Sqlerrm: '||sqlerrm);
8 -- the insert statement works in 9iR2 but the error message is -- not the one sought, how a
bout 10g ? i
9 insert into err(a,b) values (1,sys.standard.sqlerrm);
10 commit;
11 end;
12 /
PL/SQL procedure successfully completed.
SQL> select * from err;
A
B
1
ORA-0000: normal, successful completion
SQL>
Similar Messages
-
Inserting multiple rows using a single Insert statement without using dual
Hi all,
i am trying to insert multiple rows using a single insert statement like the below one.
The below one works fine..
But is there any other change that can be done in the below one without using dual...
insert all
into ps_hd_samp (num1,num2) values (1,1)
into ps_hd_samp (num1,num2) values (2,2)
into ps_hd_samp (num1,num2) values (3,3)
select 1 from dual;NiranjanSe wrote:
Hi all,
i am trying to insert multiple rows using a single insert statement like the below one.
The below one works fine..
But is there any other change that can be done in the below one without using dual...
insert all
into ps_hd_samp (num1,num2) values (1,1)
into ps_hd_samp (num1,num2) values (2,2)
into ps_hd_samp (num1,num2) values (3,3)
select 1 from dual;
SQL> create table ps_hd_samp (num1 number,num2 number);
Table created.
SQL> insert all
2 into ps_hd_samp (num1,num2) values (1,1)
3 into ps_hd_samp (num1,num2) values (2,2)
4 into ps_hd_samp (num1,num2) values (3,3)
5 select count(*)
6 from ps_hd_samp;
3 rows created.
SQL> select * from ps_hd_samp;
NUM1 NUM2
1 1
2 2
3 3 -
Using functions in insert statement
Hi,
I'm trying to insert data into an object view and I have an object date_object in one of the tables i'm inserting from. Here is the specification for date_object:
create or replace type date_object as object
(quarter number,
year number(4),
member procedure set_date(d in date_object),
member procedure set_date(v_qtr in number, v_year in number),
constructor function date_object(d in date_object) return self as result,
--overriding constructor function date_object(v_qtr number, v_year number) return self as result,
member function to_string return varchar2,
member function get_quarter return number,
member function get_year return number,
member function get_quarter_as_string return varchar2);
I'm trying to insert into my view like this:
create or replace view balance_view of balance as
(select bank_code,
b.name,
b.city,
b.state,
b.qdate.get_quarter_as_string(),
b.qdate.get_year(),
f.total_assets,
(f.current_liabilities + f.long_term_liabilities)
from banks b join financial_data f using(bank_code));
b.qdate is a date object from the banks table, i'm trying to call a member function to insert data into my view, however i get an error like this:
ERROR at line 6:
ORA-00904: "B"."QDATE"."GET_QUARTER_AS_STRING": invalid identifier
Does anyone have an idea of what I may be doing wrong?Hi,
I think you should alias the column names when you are creating a view.
b.qdate.get_quarter_as_string(),
b.qdate.get_year(),
(f.current_liabilities + f.long_term_liabilities) These three cannot be the name of the columns in the view.
Can you please try that?
I tried the following example and it is working fine.
SQL> create type date_type as object(
2 date_of_birth date,
3 map member function get_age return number);
4 /
Type created.
SQL> create type body date_type as
2 map member function get_age return number is
3 Begin
4 return trunc((sysdate-date_of_birth)/365);
5 end;
6 end;
7 /
Type body created.
SQL> create table person(
2 id number,
3 name varchar2(20),
4 dob date_type);
Table created.
1* insert into person values (1,'test',date_type(to_date('01-01-1985','dd-mm-yyyy')))
SQL> /
1 row created.
SQL> commit;
SQL> select p.id,p.name,p.dob.get_age() from person p;
ID NAME P.DOB.GET_AGE()
1 test 24
SQL> create view test_view as
2 select p.id,p.name,p.dob.get_age() age from person p;
View created.
SQL> select * from test_view;
ID NAME AGE
1 test 24Thanks,
Rajesh.
Added example.
Edited by: Rchamarthi on Apr 27, 2009 7:09 PM -
Query returning different number of rows standalone vs insert statement
Hi,
We are using Oracle 10g. We are facing a issue where a SELECT inserts 26294 rows when used with a insert statement. The same select (cut-and-paste) when executed standalone, returns only 60 rows. Any idea what could be causing this?
Thanks in advance,
Hari Narayanan
TIAA-CREF
See details below,
SQL> INSERT INTO cref.position_recon_breaks (
2 effective_date,
3 fund_entity_id,
4 security_alias,
5 accounting_system,
6 pace_shares,
7 accounting_sys_shares,
8 accounting_sys_unp_trd_shares
9 )
10 SELECT pr.effective_date,
11 pr.ENTITY_ID,
12 pr.SECURITY_ALIAS,
13 'MELLON',
14 CREF_SHARES PACE_SHARES,
15 CORP_SHARES ACCOUNTING_SYS_SHARES,
16 CORP_UNP_TRD_SHARES ACCOUNTING_SYS_UNP_TRD_SHARES
17 FROM cref.MELLON_POSITION_RECON pr
18 WHERE ABS(SHARES_DIFFERENCE) >= 1;
25294 rows created.
SQL> select count(*) from
2 (SELECT pr.effective_date,
3 pr.ENTITY_ID,
4 pr.SECURITY_ALIAS,
5 'MELLON',
6 CREF_SHARES PACE_SHARES,
7 CORP_SHARES ACCOUNTING_SYS_SHARES,
8 CORP_UNP_TRD_SHARES ACCOUNTING_SYS_UNP_TRD_SHARES
9 FROM cref.MELLON_POSITION_RECON pr
10 WHERE ABS(SHARES_DIFFERENCE) >= 1);
COUNT(*)
60charred/jzhang,
Thanks for your responses. Just as an additional info, MELLON_POSITION_RECON is one hell of a view - not written by me :) - with unions and inline queries.
If it would be of any help, here is the script,
CREATE OR REPLACE FORCE VIEW CREF.MELLON_POSITION_RECON
(EFFECTIVE_DATE, FUND_CODE, ENTITY_ID, ENTITY_NAME, SECURITY_ALIAS,
SECURITY_NAME, PRIMARY_ASSET_ID, CREF_SECURITY_COUNT, CORP_SECURITY_COUNT, CREF_CURRENCY_CODE,
CORP_CURRENCY_CODE, CREF_EXCHANGE_RATE, CORP_EXCHANGE_RATE, CREF_SHARES, CORP_SHARES,
CREF_PRICE_LOCAL, CORP_PRICE_LOCAL, CREF_MARKET_VALUE_USD, CORP_MARKET_VALUE_USD, CREF_MARKET_VALUE_LOCAL,
CORP_MARKET_VALUE_LOCAL, CREF_ACCRUED_INCOME_USD, CORP_ACCRUED_INCOME_USD, CORP_UNP_TRD_MARKET_VALUE, CORP_UNP_TRD_SHARES,
SHARES_DIFFERENCE, SHARES_DIFF_INCL_UNP, LOCAL_PRICE_DIFFERENCE, MKT_VALUE_USD_DIFF, MKT_VALUE_USD_DIFF_INCL_UNP,
ACCRUED_INCOME_DIFF)
AS
SELECT /*+ ORDERED */
P.EFFECTIVE_DATE
,E.CODE FUND_CODE
,P.ENTITY_ID
,E.LONG_NAME ENTITY_NAME
,P.SECURITY_ALIAS
,S.ISSUE_NAME SECURITY_NAME
,S.PRIMARY_ASSET_ID
,P.CREF_SECURITY_COUNT
,P.CORP_SECURITY_COUNT CORP_SECURITY_COUNT
,P.CREF_CURRENCY_CODE
,P.CORP_CURRENCY_CODE CORP_CURRENCY_CODE
,P.CREF_EXCHANGE_RATE
,P.CORP_EXCHANGE_RATE CORP_EXCHANGE_RATE
,P.CREF_SHARES
,P.CORP_SHARES CORP_SHARES
,P.CREF_PRICE_LOCAL
,P.CORP_PRICE_LOCAL CORP_PRICE_LOCAL
,ROUND(P.CREF_MARKET_VALUE_USD,2) CREF_MARKET_VALUE_USD
,P.CORP_MARKET_VALUE_USD CORP_MARKET_VALUE_USD
,ROUND(P.CREF_MARKET_VALUE_LOCAL,2) CREF_MARKET_VALUE_LOCAL
,P.CORP_MARKET_VALUE_LOCAL CORP_MARKET_VALUE_LOCAL
,ROUND(P.CREF_ACCRUED_INCOME_USD,2) CREF_ACCRUED_INCOME_USD
,P.CORP_ACCRUED_INCOME_USD
,P.CORP_UNP_TRD_MARKET_VALUE
,P.CORP_UNP_TRD_SHARES
,NVL(P.CORP_SHARES, 0) - NVL(P.CREF_SHARES, 0) SHARES_DIFFERENCE
,NVL(P.CORP_SHARES,0) +
(NVL(P.CORP_UNP_TRD_SHARES, 0) - NVL(P.CREF_SHARES, 0)) SHARES_DIFF_INCL_UNP
,NVL(P.CREF_PRICE_LOCAL, 0) - NVL(P.CORP_PRICE_LOCAL, 0) LOCAL_PRICE_DIFFERENCE
,NVL(ROUND(P.CREF_MARKET_VALUE_USD,2),0) - NVL(P.CORP_MARKET_VALUE_USD,0) MKT_VALUE_USD_DIFF
,NVL(ROUND(P.CREF_MARKET_VALUE_USD,2),0) -
(NVL(P.CORP_MARKET_VALUE_USD, 0) + NVL(P.CORP_UNP_TRD_MARKET_VALUE,0)) MKT_VALUE_USD_DIFF_INCL_UNP
,NVL(ROUND(P.CREF_ACCRUED_INCOME_USD,2),0) - NVL(P.CORP_ACCRUED_INCOME_USD, 0) ACCRUED_INCOME_DIFF
FROM
SELECT ENTITY_ID
,EFFECTIVE_DATE
,SECURITY_ALIAS
,SUM(CREF_SECURITY_COUNT) CREF_SECURITY_COUNT
,SUM(CORP_SECURITY_COUNT) CORP_SECURITY_COUNT
,MAX(CREF_CURRENCY_CODE) CREF_CURRENCY_CODE
,MAX(CORP_CURRENCY_CODE) CORP_CURRENCY_CODE
,MAX(CREF_EXCHANGE_RATE) CREF_EXCHANGE_RATE
,MAX(CORP_EXCHANGE_RATE) CORP_EXCHANGE_RATE
,SUM(CREF_SHARES) CREF_SHARES
,SUM(CORP_SHARES) CORP_SHARES
,MAX(CREF_PRICE_LOCAL) CREF_PRICE_LOCAL
,MAX(CORP_PRICE_LOCAL) CORP_PRICE_LOCAL
,SUM(CREF_MARKET_VALUE_USD) CREF_MARKET_VALUE_USD
,SUM(CORP_MARKET_VALUE_USD) CORP_MARKET_VALUE_USD
,SUM(CREF_MARKET_VALUE_LOCAL) CREF_MARKET_VALUE_LOCAL
,SUM(CORP_MARKET_VALUE_LOCAL) CORP_MARKET_VALUE_LOCAL
,SUM(CREF_ACCRUED_INCOME_USD) CREF_ACCRUED_INCOME_USD
,SUM(CORP_ACCRUED_INCOME_USD) CORP_ACCRUED_INCOME_USD
,MIN(QUERY_TIMESTAMP) QUERY_TIMESTAMP
,SUM(CORP_UNP_TRD_MARKET_VALUE) CORP_UNP_TRD_MARKET_VALUE
,SUM(CORP_UNP_TRD_SHARES) CORP_UNP_TRD_SHARES
FROM
SELECT -- WANT ONE ROW PER FUND PER SECURITY
/*+ index(p I_POS_ENTID_SRCINTFC_CREF) index (pd) */
E.FUND_ENTITY_ID ENTITY_ID
,P.EFFECTIVE_DATE
,PD.SECURITY_ALIAS
,SYSDATE QUERY_TIMESTAMP
,1 CREF_SECURITY_COUNT
,MAX(PD.LOCAL_CURRENCY) CREF_CURRENCY_CODE
,MAX(PD.MKT_EXCHANGE_RATE) CREF_EXCHANGE_RATE
,SUM(PD.SHARE_PAR_VALUE) CREF_SHARES
,MAX(PD.PRICE) CREF_PRICE_LOCAL
,SUM(PD.MARKET_VALUE) CREF_MARKET_VALUE_USD
,SUM(PD.LOCAL_MARKET_VALUE) CREF_MARKET_VALUE_LOCAL
,SUM(PD.ACCRUED_INCOME) CREF_ACCRUED_INCOME_USD
,0 CORP_SECURITY_COUNT
,TO_CHAR(NULL) CORP_CURRENCY_CODE
,0 CORP_SHARES
,TO_NUMBER(NULL) CORP_PRICE_LOCAL
,TO_NUMBER(NULL) CORP_EXCHANGE_RATE
,0 CORP_MARKET_VALUE_USD
,0 CORP_MARKET_VALUE_LOCAL
,0 CORP_ACCRUED_INCOME_USD
,0 CORP_UNP_TRD_MARKET_VALUE
,0 CORP_UNP_TRD_SHARES
FROM CREF.ENTITY E,
CREF.ENTITY EF fund entity NF
,HOLDINGDBO.POSITION P
,(SELECT MAX(EFFECTIVE_DATE) CURRENT_DATE
FROM HOLDINGDBO.POSITION P,
PACE_MASTERDBO.INTERFACES I
WHERE I.SHORT_DESC = 'MELLON'
AND I.INSTANCE = P.SRC_INTFC_INST) DT
,HOLDINGDBO.POSITION_DETAIL PD
,PACE_MASTERDBO.INTERFACES I
WHERE E.PORTFOLIO_ENTITY_TYPE_CODE = 'PORT'
AND E.ENTITY_ID = P.ENTITY_ID
AND EF.ENTITY_ID = E.FUND_ENTITY_ID -- NF
AND EF.ACCOUNTING_SYSTEM = 'MELLON' -- NF
AND E.ENTITY_ID = P.ENTITY_ID
AND I.SHORT_DESC = 'STARDIRECT'
AND I.INSTANCE = P.SRC_INTFC_INST
AND P.EFFECTIVE_DATE = DT.CURRENT_DATE
AND P.POSITION_ID = PD.POSITION_ID
-- "GROUP BY" COMBINES THE LONG AND SHORT POSITIONS
GROUP BY P.EFFECTIVE_DATE, E.FUND_ENTITY_ID, PD.SECURITY_ALIAS
UNION ALL
SELECT -- CORPORATE SENDS ONE ROW PER FUND PER SECURITY (NO SHORTS)
/*+ index(p I_POS_ENTID_SRCINTFC_CREF) index (pd) */
E.ENTITY_ID
,P.EFFECTIVE_DATE
,PD.SECURITY_ALIAS
,SYSDATE QUERY_TIMESTAMP
,0 CREF_SECURITY_COUNT
,TO_CHAR(NULL) CREF_CURRENCY_CODE
,0 CREF_SHARES
,TO_NUMBER(NULL) CREF_PRICE_LOCAL
,TO_NUMBER(NULL) CREF_EXCHANGE_RATE
,0 CREF_MARKET_VALUE_USD
,0 CREF_MARKET_VALUE_LOCAL
,0 CREF_ACCRUED_INCOME_USD
,1 CORP_SECURITY_COUNT
,PD.LOCAL_CURRENCY CORP_CURRENCY_CODE
,PD.SHARE_PAR_VALUE CORP_SHARES
,PD.PRICE CORP_PRICE_LOCAL
,pd.mkt_exchange_rate CORP_EXCHANGE_RATE
,PD.MARKET_VALUE CORP_MARKET_VALUE_USD
,PD.LOCAL_MARKET_VALUE CORP_MARKET_VALUE_LOCAL
,PD.ACCRUED_INCOME CORP_ACCRUED_INCOME_USD
,0 CORP_UNP_TRD_MARKET_VALUE
,0 CORP_UNP_TRD_SHARES
FROM CREF.ENTITY E
,HOLDINGDBO.POSITION P
,(SELECT MAX(EFFECTIVE_DATE) CURRENT_DATE
FROM HOLDINGDBO.POSITION P,
PACE_MASTERDBO.INTERFACES I
WHERE I.SHORT_DESC = 'MELLON'
AND I.INSTANCE = P.SRC_INTFC_INST) DT
,HOLDINGDBO.POSITION_DETAIL PD
,PACE_MASTERDBO.INTERFACES I
WHERE E.FUND_FLAG = 'Y' --
AND E.ENTITY_ID = P.ENTITY_ID
AND I.SHORT_DESC = 'MELLON'
AND I.INSTANCE = P.SRC_INTFC_INST
AND P.EFFECTIVE_DATE = DT.CURRENT_DATE
AND P.POSITION_ID = PD.POSITION_ID
UNION ALL
SELECT
UTS.FUND_ENTITY_ID ENTITY_ID
,UTS.EFFECTIVE_DATE
,UTS.SECURITY_ALIAS
,SYSDATE QUERY_TIMESTAMP
,0 CREF_SECURITY_COUNT
,TO_CHAR(NULL) CREF_CURRENCY_CODE
,0 CREF_SHARES
,TO_NUMBER(NULL) CREF_PRICE_LOCAL
,TO_NUMBER(NULL) CREF_EXCHANGE_RATE
,0 CREF_MARKET_VALUE_USD
,0 CREF_MARKET_VALUE_LOCAL
,0 CREF_ACCRUED_INCOME_USD
,0 CORP_SECURITY_COUNT
,TO_CHAR(NULL) CORP_CURRENCY_CODE
,0 CORP_SHARES
,TO_NUMBER(NULL) CORP_PRICE_LOCAL
,TO_NUMBER(NULL) CORP_EXCHANGE_RATE
,0 CORP_MARKET_VALUE_USD
,0 CORP_MARKET_VALUE_LOCAL
,0 CORP_ACCRUED_INCOME_USD
,UTS.SUM_MARKET_VALUE CORP_UNP_TRD_MARKET_VALUE
,UTS.SUM_SHARES CORP_UNP_TRD_SHARES
FROM
(SELECT MAX(EFFECTIVE_DATE) CURRENT_DATE
FROM HOLDINGDBO.POSITION P,
PACE_MASTERDBO.INTERFACES I
WHERE I.SHORT_DESC = 'MELLON'
AND I.INSTANCE = P.SRC_INTFC_INST) DT
,cref.UNPROCESSED_TRADES_SUM UTS
WHERE DT.CURRENT_DATE = UTS.EFFECTIVE_DATE
AND UTS.UPDATED_BY = 'MELLON'
GROUP BY EFFECTIVE_DATE, ENTITY_ID, SECURITY_ALIAS
) P,
cref.ENTITY E,
SECURITYDBO.SECMASTER_HISTORY S
WHERE P.ENTITY_ID = E.ENTITY_ID
AND P.SECURITY_ALIAS = S.SECURITY_ALIAS
AND S.SRC_INTFC_INST = (SELECT INSTANCE FROM PACE_MASTERDBO.INTERFACES
WHERE SHORT_DESC = 'EAGLE PACE')
AND S.EFFECTIVE_DATE = (SELECT MAX(S1.EFFECTIVE_DATE)
FROM SECURITYDBO.SECMASTER_HISTORY S1
WHERE S1.SRC_INTFC_INST = S.SRC_INTFC_INST
AND S1.SECURITY_ALIAS = S.SECURITY_ALIAS
AND S1.EFFECTIVE_DATE <= P.EFFECTIVE_DATE); -
hi,
i have used script for insert statement.while compiling it ,it shows error in declare section that to in t24_customer_code.can any body pls check out and tell me.
the script is ....
DECLARE
a NUMBER := 10;
t24_customer_code NUMBER;
my_tab SYS.dbms_debug_vc2coll := SYS.dbms_debug_vc2coll ();
BEGIN
LOOP
EXIT WHEN a > 20;
a := a + 1;
t24_customer_code:= 9700 + a;
INSERT INTO t24_customer
(t24_customer_code,
T24_MNEMONIC,
T24_SHORT_NAME,
T24_NAME_1,
T24_NAME_2,
T24_STREET,
T24_SECTOR,
T24_ACCOUNT_OFFICER,
T24_OTHER_OFFICER,
T24_INDUSTRY,
T24_TARGET,
T24_NATIONALITY,
T24_CUSTOMER_STATUS,
T24_LANGUAGE)
VALUES
(t24_customer_code,
'MNEMON' || a,
'HANSARUN',
'KUMAR',
'MAQSOOD',
'NIYAZ DINESH',
1001,
1,
5,
1000,
1,
'US',
2,
'US');
my_tab.EXTEND;
my_tab (a - 1) := t24_customer_code;
END LOOP;
OPEN :cur FOR
SELECT *
FROM t24_customer
WHERE t24_customer_code IN (SELECT COLUMN_VALUE
FROM TABLE (CAST (my_tab AS SYS.dbms_debug_vc2coll)));
END;
thanks
ratheeshPlease describe column name and data type on your table.
T24_MNEMONIC is not NUMBER, is it?
By the way,
VALUES
(t24_customer_code,Here t24_customer_code is not your variable
but that is column name of t24_customer.
You might get another error after solving 'ORA-01722: invalid number'
SQL> edit
Wrote file afiedt.buf
1* insert into scott.dept (deptno) values (deptno)
SQL> /
insert into scott.dept (deptno) values (deptno)
ERROR at line 1:
ORA-00984: column not allowed here -
How to tune the Insert statement?
Hi ,
I am using 10.2.0.4.0 version of oracle.
i am having one insert statement , which comes almost all the time in the TOP of my AWR elapsed time section.
And its somewhat similar to as below.
Query:
INSERT INTO a (InvoicePK, CheckPK)
SELECT DISTINCT ih.InvoicePK, cd.CheckPK
FROM at,
cd,
ih,
rd
WHERE at.AttachmentPK = :1
AND cd.CheckPK = at.CheckPK
AND at.AttachmentPK = rd.AttachPK
AND ih.PAYPK = cd.PAYEEPAYPK
AND ih.PayerNS = cd.PayerNS
AND ih.PayerPayId = cd.PayerPayId
AND ih.UpperInvoiceNum = rd.UPPERINVNUM
AND ih.InvoiceStatusCD NOT IN ('REJ', 'DNY');
Below is the plan for the 'Select ' statement i.e. used in the insert statement.
Execution Plan:
Plan hash value: 2232002808
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time | Pstart| Pstop |
| 0 | SELECT STATEMENT | | 1 | 193 | 9 (23)| 00:00:01 | | |
| 1 | HASH UNIQUE | | 1 | 193 | 9 (23)| 00:00:01 | | |
|* 2 | HASH JOIN | | 1 | 193 | 8 (13)| 00:00:01 | | |
| 3 | NESTED LOOPS | | 10 | 1740 | 4 (0)| 00:00:01 | | |
| 4 | NESTED LOOPS | | 1 | 85 | 3 (0)| 00:00:01 | | |
| 5 | TABLE ACCESS BY INDEX ROWID | at | 1 | 16 | 2 (0)| 00:00:01 | | |
|* 6 | INDEX UNIQUE SCAN | atpk1 | 1 | | 1 (0)| 00:00:01 | | |
| 7 | TABLE ACCESS BY INDEX ROWID | cd | 7359K| 484M| 1 (0)| 00:00:01 | | |
|* 8 | INDEX UNIQUE SCAN | cdpk1 | 1 | | 1 (0)| 00:00:01 | | |
|* 9 | TABLE ACCESS BY GLOBAL INDEX ROWID| ih | 10 | 890 | 2 (0)| 00:00:01 | ROWID | ROWID |
|* 10 | INDEX RANGE SCAN | IH_PAYPK_PAYERNS_PAYID | 5 | | 1 (0)| 00:00:01 | | |
| 11 | TABLE ACCESS BY INDEX ROWID | rd | 9 | 171 | 3 (0)| 00:00:01 | | |
|* 12 | INDEX RANGE SCAN | IDX_rd | 9 | | 2 (0)| 00:00:01 | | |
Predicate Information (identified by operation id):
2 - access("IH"."UPPERINVOICENUM"="RD"."UPPERINVNUM")
6 - access("AT"."ATTACHMENTPK"=7794833983)
8 - access("CD"."CHECKPK"="AT"."CHECKPK")
9 - filter("IH"."INVOICESTATUSCD"<>'REJ' AND "IH"."INVOICESTATUSCD"<>'DNY')
10 - access("IH"."PAYPK"="CD"."PAYEEPAYPK" AND "IH"."PAYERNS"="CD"."PAYERNS" AND "IH"."PAYERPAYID"="CD"."PAYERPAYID")
12 - access("RD"."ATTACHPK"=7794833983)
Statistics
1 recursive calls
0 db block gets
71 consistent gets
0 physical reads
0 redo size
316 bytes sent via SQL*Net to client
240 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
3 rows processed
The 'select' Statement executes with in seconds resulting 3 distinct records, but the insert statement takes ~20sec(Elaps time per execution
as shown in AWR report) for one time execution, so what must be the reason , and how should i proceed to resolve this performance issue?You can do as follows:
- Enable trace
- execute the insert statement
- use tkprof (and put the results here) to see where's its taking long
Also, while insert is being executed, what are the wait events you see ?
I dont think there is problem with plan. -
Question on Creating Table From Insert statement
Hi,
I want to create a table using a DBlink from another database using the create/insert statement. Will it also transfer the constraints or do I have to do it manually afterwards? Thanks.
Create table T1
SELECT a,b,c from T2 from DB@dblink;As discussed above, the constraints, indexes, triggers are not copied. Only NOT NULL constraints are copied.
Look at this thread Re: Copying table structure.
for copying triggers/indexes from source table to destination table.
Thanks,
Navaneeth -
Nologging for insert statement
Hello,
Is it possible to use NOLOGGING with INSERT statement?
For example:
INSERT /*+ APPEND PARALLEL(test,4)*/INTO test NOLOGGING (select .....)
It will take NOLOGGING as alias name of table or what is correct way to use NOLOGGING for insert statement.There is no such thing as a NOLOGGING hint (or insert keyword as you've tried it).
You must use ALTER TABLE table_name NOLOGGING; -
Using of bulk insert create problem
How to use the bulk insert statement in my jsp and which should be updated into the database.
I've tried this one:
bulk insert test from test1.txt with (fieldterminator=':')but it gives an error as:
u don't have permission to use bulk statement.
Could any1 get me rid off from this problem.
in advance thanks.....Most likely the person responsible for permissions in your database could help you out there. If you're here looking for a way to execute commands that you aren't authorized to execute, you are wasting your time.
-
Extract statement and insert statement
can anyone explain me the use of this insert statement and extract statement.
INSERT lfa1-name1 INTO fg01
extract fg01.
thanks
phyroseHi,
From f1 help....
EXTRACT
Basic form
EXTRACT fg.
Effect
Writes all fields of the field group fg (FIELD-GROUPS) as an entry in asequential dataset. If you have defined a field group HEADER,its fields precede each entry as a sort key. Afterwards, you canuse SORT and LOOP ... ENDLOOP to sort or process the datasetrespectively. No further EXTRACT statements are possible afterthis.
Notes
General:
As soon as you have extracted a dataset using EXTRACT, you canno longer extend the field group using INSERT. In particular, you cannot change the HEADERfield group at all after the first EXTRACT (regardless of thefield group to which it applied).
Large extract datasets are not stored in main memory. Instead, theyare kept in an external auxiliary file. You can set the directory inwhich this file is created using the SAP profile parameterDIR_EXTRACT. The default directory is the SAP data directory(SAP profile parameter DIR_DATA).
Notes
Runtime errors:
EXTRACT_AFTER_SORT/LOOP: EXTRACT after SORT, orLOOP. EXTRACT_BUFFER_NO_ROLL: Unable to create the required main
EXTRACT_FIELD_TOO_LARGE: Occupied length of a field is toolarge.
EXTRACT_HEADER_NOT_UNIQUE: Field group HEADER wasmodified after an EXTRACT statement.
EXTRACT_OPEN_EXTRACTFILE_OPEN:
Error opening the external extract dataset file.
EXTRACT_RESOURCEHANDLER_FAILED: Error deleting the externalextract dataset file.
EXTRACT_TOO_LARGE: Total length of the entry for extraction(including HEADER fields) is too large.
Additional help
Filling anExtract with Data
Extracts
Since internal tables have fixed line structures, they are not suited to handle data sets with varying structures. Instead, you can use extract datasets for this purpose.
An extract is a sequential dataset in the memory area of the program. You can only address the entries in the dataset within a special loop. The index or key access permitted with internal tables is not allowed. You may only create one extract in any ABAP program. The size of an extract dataset is, in principle, unlimited. Extracts larger than 500KB are stored in operating system files. The practical size of an extract is up to 2GB, as long as there is enough space in the filesystem.
An extract dataset consists of a sequence of records of a pre-defined structure. However, the structure need not be identical for all records. In one extract dataset, you can store records of different length and structure one after the other. You need not create an individual dataset for each different structure you want to store. This fact reduces the maintenance effort considerably.
In contrast to internal tables, the system partly compresses extract datasets when storing them. This reduces the storage space required. In addition, you need not specify the structure of an extract dataset at the beginning of the program, but you can determine it dynamically during the flow of the program.
You can use control level processing with extracts just as you can with internal tables. The internal administration for extract datasets is optimized so that it is quicker to use an extract for control level processing than an internal table.
Procedure for creating an extract:
Define the record types that you want to use in your extract by declaring them as field groups. The structure is defined by including fields in each field group.
Defining an Extract
Fill the extract line by line by extracting the required data.
Filling an Extract with Data
Once you have filled the extract, you can sort it and process it in a loop. At this stage, you can no longer change the contents of the extract.
Processing Extracts
INSERT Statement
The INSERT statement is used to insert values into a single database table.
<insert statement> ::= INSERT INTO <table name> <insert column list> <insert source>.
<insert source> ::= VALUES '(' <value> ( ',' <value> )* ')'
| <query specification>.
<value> ::= <value expression>
| <dynamic parameter specification>
| NULL.
<insert column list> ::= '(' <column name> ( ',' <column name> )* ')'.
In Open SQL the <insert column list> is not optional.
You cannot specify string literals as values for CLOB columns. Hex literals are not supported in Open SQL.
Examples
INSERT INTO employees (employee_id, employee_name)
VALUES (4711, 'John Smith')
Inserting Values. A new row is inserted into the table employees with the values 4711 and 'John Smith' for the columns employee_id and employee_name respectively.
INSERT INTO well_paid_employees (employee_id, salary)
SELECT employee_id, salary
FROM employees
WHERE salary > ?
Inserting the Result of a Query. The employee_idand the salaryof all employees from table employeeswith a salary exceeding a certain value are inserted into the table well_paid_employees.
Regards -
Use NEXTVAL in an insert statement Part II
db - 10g
I am asking this question out of curiosity.
I posted a question and recieved a successful answer at the following address on this forum;
Use NEXTVAL in an insert statement
The following insert statement uses a sequence to create an arbitrary number for each null record. The problem is, the sequence is firing regardless of the condition being true or false (but it is working in that it only inserts values when the condition is true). The result is the sequence appears to increment each time it loops through the cursor and so the first arbitrary number to be inserted is not 1001 but some other higher number.
INSERT INTO psp_trees
( plot_id
, tree_name
, species_code)
VALUES
( get_plot_id
, c1.treenum
, c1.species
) RETURNING tree_id INTO get_tree_id; I have gotten around the issue by removing the sequence from the insert statement and placing it outside the cursor loop as an update statement.
UPDATE psp_trees
SET tree_name = to_char(tree_arbitrary_name_seq.nextval)
WHERE tree_name IS NULL;Is there anyway to get the sequence to only fire in the insert statement when the condition is true.
This is the complete anonymous block for your reference;
DECLARE p_access_num NUMBER;
col_access_var VARCHAR2(30);
type number_ptb IS table OF VARCHAR2(4000);
p_access_nam number_ptb;
get_plot_measurement_id NUMBER;
update_plot_measurements VARCHAR2(4000);
get_tree_id NUMBER;
get_plot_id NUMBER;
BEGIN
p_access_num := 6;
p_access_nam := number_ptb();
p_access_nam.extend(7);
p_access_nam(1) := 535;
p_access_nam(2) := 548;
p_access_nam(3) := 898;
p_access_nam(4) := 544;
p_access_nam(5) := 551;
p_access_nam(6) := 724;
FOR loop_int IN 1 .. p_access_num
LOOP
col_access_var := p_access_nam(loop_int);
-- 1. Initiate insert process by getting PK from psp_plots.
SELECT plot_id INTO get_plot_id FROM psp_plots WHERE plot_name = col_access_var;
-- 2. Insert records into psp_plot_measurements and keep relationship with psp_plots with variable get_plot_id.
-- and get primary key value of psp_plot_measurements to insert into psp_tree_measurements during loop process.
INSERT INTO psp_plot_measurements (plot_id) VALUES (get_plot_id) RETURNING plot_measurement_id INTO get_plot_measurement_id;
-- 3. Update record created at point 2.
UPDATE psp_plot_measurements
SET measurement_date = (SELECT DISTINCT date_ FROM pspdata)
, codominant_height = (SELECT DISTINCT height_codom FROM pspdata)
, assessor = (SELECT DISTINCT assessor FROM pspdata)
WHERE plot_measurement_id = col_access_var
-- 4. Open cursor to insert rows one at a time and maintain relationships between related tables.
FOR c1 IN (SELECT treenum
, dbhob
, treecomments
, species
FROM pspdata
WHERE plotnumber = col_access_var
AND date_ IS NOT NULL)
LOOP
-- 5. Insert record into psp_trees
-- and get primary key value of psp_trees to insert into psp_tree_measurements.
INSERT INTO psp_trees
( plot_id
, tree_name
, species_code)
VALUES
( get_plot_id
, c1.treenum
--, NVL(c1.treenum , to_char(tree_arbitrary_name_seq.nextval))
--, (CASE WHEN c1.treenum IS NULL THEN to_char(tree_arbitrary_name_seq.nextval) ELSE c1.treenum END)
, c1.species
) RETURNING tree_id INTO get_tree_id;
-- 6. Insert records into psp_tree_measurements and keep relationship with psp_trees with variable get_tree_id.
INSERT INTO psp_tree_measurements
( plot_measurement_id
, tree_id
, dbhob
, comments
VALUES
( get_plot_measurement_id
, get_tree_id
, c1.dbhob
, c1.comment
END LOOP;
END LOOP;
-- 7. Update null columns with arbitrary number.
UPDATE psp_trees
SET tree_name = to_char(tree_arbitrary_name_seq.nextval)
WHERE tree_name IS NULL;
END;
/Edited by: benton on Sep 6, 2011 1:53 PMOr use a function (I'll use dbms_xml.getxml):
SQL> create sequence s_seq nocache
Sequence created.
SQL> select case when mod (level, 2) = 0
then extractvalue(dbms_xmlgen.getxmltype('select s_seq.nextval from dual'), '//text()')
else '0' end col1
from dual connect by level < 20
COL1
0
1
0
2
0
3
0
4
0
5
0
6
0
7
0
8
0
9
0
19 rows selected.
SQL> select sequence_name, last_number from user_sequences where sequence_name = 'S_SEQ'
SEQUENCE_NAME LAST_NUMBER
S_SEQ 10
1 row selected. -
Insert statement taking time on oracle 10g
Hi,
My procedure taking time in following statement while database upgrading from oracle 9i to oracle 10g.
I m using oracle version 10.2.0.4.0.
cust_item is matiralize view in procedure and it is refreshing in the procedure
Index is dropping before inserting data into cust_item_tbl TABLE and after inserting data index is created.
There are almost 6 lac records into MV which are going to insert into TABLE.
In 9i below insert statement is taking 1 hr time to insert while in 10g it is taking 2.30 hrs.
EXECUTE IMMEDIATE 'ALTER SESSION ENABLE PARALLEL QUERY';
EXECUTE IMMEDIATE 'ALTER SESSION ENABLE PARALLEL DML';
INSERT INTO /*+ APPEND PARALLEL */ cust_item_tbl NOLOGGING
(SELECT /*+ PARALLEL */
ctry_code, co_code, srce_loc_nbr, srce_loc_type_code,
cust_nbr, item_nbr, lu_eff_dt,
0, 0, 0, lu_end_dt,
bus_seg_code, 0, rt_nbr, 0, '', 0, '', SYSDATE, '', SYSDATE,
'', 0, ' ',
case
when cust_nbr in (select distinct cust_nbr from aml.log_t where CTRY_CODE = p_country_code and co_code = p_company_code)
THEN
case
when trunc(sysdate) NOT BETWEEN trunc(lu_eff_dt) AND trunc(lu_end_dt)
then NVL((select cases_per_pallet from cust_item c where c.ctry_code = a.ctry_code and c.co_code = a.co_code
and c.cust_nbr = a.cust_nbr and c.GTIN_CO_PREFX = a.GTIN_CO_PREFX and c.GTIN_ITEM_REF_NBR = a.GTIN_ITEM_REF_NBR
and c.GTIN_CK_DIGIT = a.GTIN_CK_DIGIT and trunc(sysdate) BETWEEN trunc(c.lu_eff_dt) AND trunc(c.lu_end_dt) and rownum = 1),
a.cases_per_pallet)
else cases_per_pallet
end
else cases_per_pallet
END cases_per_pallet,
cases_per_layer
FROM cust_item a
WHERE a.ctry_code = p_country_code ----varible passing by procedure
AND a.co_code = p_company_code ----varible passing by procedure
AND a.ROWID =
(SELECT MAX (b.ROWID)
FROM cust_item b
WHERE b.ctry_code = a.ctry_code
AND b.co_code = a.co_code
AND b.ctry_code = p_country_code ----varible passing by procedure
AND b.co_code = p_company_code ----varible passing by procedure
AND b.srce_loc_nbr = a.srce_loc_nbr
AND b.srce_loc_type_code = a.srce_loc_type_code
AND b.cust_nbr = a.cust_nbr
AND b.item_nbr = a.item_nbr
AND b.lu_eff_dt = a.lu_eff_dt));explain plan of oracle 10g
Plan
INSERT STATEMENT CHOOSECost: 133,310 Bytes: 248 Cardinality: 1
5 FILTER
4 HASH GROUP BY Cost: 133,310 Bytes: 248 Cardinality: 1
3 HASH JOIN Cost: 132,424 Bytes: 1,273,090,640 Cardinality: 5,133,430
1 INDEX FAST FULL SCAN INDEX MFIPROCESS.INDX_TEMP_CUST_AUTH_PERF_MV Cost: 10,026 Bytes: 554,410,440 Cardinality: 5,133,430
2 MAT_VIEW ACCESS FULL MAT_VIEW MFIPROCESS.TEMP_CUST_AUTH_PERF_MV Cost: 24,570 Bytes: 718,680,200 Cardinality: 5,133,430 can you please look into the issue?
Thanks.According to the execution plan you posted parallelism is not taking place - no parallel operations listed
Check the hint syntax. In particular, "PARALLEL" does not look right.
Running queries in parallel can either help performance, hurt performance, or do nothing for performance. In your case a parallel index scan on MFIPROCESS.INDX_TEMP_CUST_AUTH_PERF_MV using the PARALLEL_INDEX hint and the PARALLEL hint specifying the table for MAT_VIEW MFIPROCESS.TEMP_CUST_AUTH_PERF_MV Cost might help, something like (untested)
select /*+ PARALLEL_INDEX(INDX_TEMP_CST_AUTH_PERF_MV) PARALLEL(TEMP_CUST_AUTHPERF_MV) */Is query rewrite causing the MVs to be read? If so hinting the query will be tricky -
Using insert statements for creating objects..pls help
Hello all,
I have 2 databases DB1 (which is running on 8i) and DB2( Running on 10G).
How can I copy all the objects of a particular schema (user1) from DB1 to DB2, only by using INSERT statements. I do not want to use import/export since it is taking huge time for the operation.
Could anybody help me on this?
Regards,
chotuSince I have allready imported indexes,procedures etc , now I need only to copy tables from DB1 to DB2.
I have truncated all the tables of user1 in DB2
Now I am using,
insert into my_tab as select * from user1.my_tab@DB2_db_link;
Thanks for the help...
chotu. -
Using the Insert statement in a Java program without hardcoding the data
hello.
this is james mcfadden. i have developed a program called Demo.java, which is used with another program called QueryTableModel.java (a program that allows data to be viewed in a JTable). The Demo.java program displays a menu, connects to a database, allows the user to add data into the database and allows the user to view data that is already in the database. I have a problem with the Demo.java program. I have hardcoded the Insert statement in it. How do you use the Insert statement to put data into a database without hardcoding the data?
import java.awt.*;//Contains all of the classes for creating user interfaces and for painting graphics and images
import java.awt.event.*;//Provides interfaces and classes for dealing with different types of events fired by AWT components
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
import javax.swing.JOptionPane;//provides a class that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";//a static variable that allows a connection to be made to a database called VideoLibrary
static Statement stmt;//a static variable that allows a statement to be made once a connection is set up
static Connection con;//a static interface that allows a connection to be made to a database
//global variables
JTextField hostField;//a class that allows a line of text to be changed
JTextField queryField;//a class that allows a line of text to be changed
QueryTableModel qtm;//a class that shows and changes regular two-dimensional tables of cells
JComboBox comboBox;//a class that puts a button or editable field and a drop-down list together
public static void main(String args[]){
int choice=-1;//a variable of type int that is set to -1
do{
choice=getChoice();//invokes the method getChoice()
if(choice!=0){
getSelected(choice);//invokes the method getSelected(choice)
}//end if
//if the user chooses 5, it will cause him or her to exit the system
}while(choice!=5);//end do-while
System.exit(0);//closes down the menu screen
}//end main
public static int getChoice(){
String choice;//a variable of type string
int ch;//a variable of type int
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");//asks the user for some input
ch = Integer.parseInt(choice);//a class that wraps a value of the primitive type int in an object
return ch;//a method that returns an integer value
}//end getChoice
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();//invokes the method maintainProductDetails()
}//end if
if(choice==2){
maintainMemberDetails();//invokes the method maintainMemberDetails()
}//end if
if(choice==3){
maintainRentalDetails();//invokes the method maintainRentalDetails()
}//end if
if(choice==4){
Demo test = new Demo();//invokes the constructor Demo()
test.setVisible(true);//shows the JTable component by marking it as visible
}//end if
}//end getSelected
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used to create a JDBC connection using a database
}//end try
catch(java.lang.ClassNotFoundException e){//causes an exception to be thrown when an application tries to load in a class through its string name
System.err.print("ClassNotFoundException: ");//displays an error message
System.err.println(e.getMessage());//returns the exception that was raised if an error occurred while attempting to load the ClassNotFoundException class
}//end catch
try {
con=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
return con;
}//end getConnection
public static void maintainProductDetails(){
Connection con = getConnection();//creates a connection with the database
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;//string variables that represent information about the different types of product data that will be stored in the database
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, 'Pussy Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainProductDetails
public static void maintainMemberDetails(){
Connection con = getConnection();//creates a connection with the database
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;//string variables that represent information about the member data that will be stored in the database
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainMemberDetails
public static void maintainRentalDetails(){
Connection con = getConnection();//creates a connection with the database
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;//string variables that represent information about the loan data that will be stored in the database
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();//Creates a Statement object for sending SQL statements to the database
//statements are allowed to be made once a connection is set up
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();//closes the Statement object
con.close();//terminates the connection with the database
}//end try
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());//returns an SQL error message
}//end catch
}//end maintainRentalDetails
public Demo(){//a constructor
super("Demo Test Frame");//overrides the constructor
setSize(350, 200);//Resizes this component so that it has width of 350 and height of 200
comboBox = new JComboBox();//invokes the class JComboBox
comboBox.addItem("jdbc:odbc:VideoLibrary");//adds the specified item to the end of the scrolling list
qtm = new QueryTableModel();//invokes the class QueryTableModel
JTable table = new JTable(qtm);//a class that shows and changes regular two-dimensional tables of cells
JScrollPane scrollpane = new JScrollPane(table);//a class that provides a scrollable view of a lightweight component
JPanel p1 = new JPanel();//a class that puts the combo box and query field in a panel
p1.setLayout(new GridLayout(3, 2));//Sets the layout manager for this container
p1.add(comboBox);//Appends the specified component to the end of this container
p1.add(new JLabel("Enter your query: "));//Appends the specified component to the end of this container
p1.add(queryField = new JTextField());//Appends the specified component to the end of this container
p1.add(new JLabel("Click here to send: "));//Appends the specified component to the end of this container
JButton jb = new JButton("Search");//a class that is an implementation of a "push" button
jb.addActionListener(new ActionListener(){//Adds an ActionListener to the button
public void actionPerformed(ActionEvent e){
qtm.setHostURL();//invokes the method setHostURL
qtm.setQuery(queryField.getText().trim());//invokes the method setQuery; and returns the text that is presented by this text component and returns a copy of the string, with leading and trailing whitespaces omitted
} );//end addActionListener
p1.add(jb);//Appends the specified component to the end of this container
getContentPane().add(p1, BorderLayout.NORTH);//Returns the content pane
getContentPane().add(scrollpane, BorderLayout.CENTER);//Returns the content pane
}//end Demo
}//end class Demo
import java.sql.*;//Provides the API for accessing and processing data stored in a data source using the Java programming language
import java.io.*;//Provides for system input and output through data streams, serialization and the file system
import java.util.Vector;//provides a class that implements a growable array of objects
import javax.swing.*;//Provides a set of lightweight components that, to the maximum degree possible, work the same on all platforms
import javax.swing.table.*;//Provides classes and interfaces for dealing with javax.swing.JTable
public class QueryTableModel extends AbstractTableModel{
Vector cache;//a class that constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
int colCount;//a variable that counts the number of columns in the three tables
String[] headers;//a class that represents character strings and all string literals in this program are implemented as instances of the String class
Connection db;//an interface that allows a connection to be made to a database
Statement statement;//an interface that allows executes the given SQL statement, which returns a single ResultSet object
String currentURL;//a variable that allows the URL to be displayed in a combo box
public QueryTableModel(){//a constructor
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//used by opening a JDBC connection using an URL
}//end try
catch(Exception e){
System.out.println("problem loading the driver ");//an error message
}//end catch
}//end QueryTableModel
public String getColumnName(int i){//Returns the designated column's name
return headers;//returns the name of each column in the three table
}//end getColumnName
public int getColumnCount(){//Returns the number of columns in the column model
return colCount;//returns the number of columns in the three tables
}//end getColumnCount
public int getRowCount(){//Returns the number of rows in this table's model
return cache.size();//returns the number of components in the vector
}//end getRowCount
public Object getValueAt(int row, int col){//Returns the cell value at row and column
return ((String[])cache.elementAt(row))[col];//Returns the component at the specified index
}//end getValueAt
public void setHostURL(){//sets the URL for the database
String url = "jdbc:odbc:VideoLibrary";//a variable that allows a connection to be made to a database called VideoLibrary
closeDB();//invokes the method closeDB()
try{
db=DriverManager.getConnection(url,"","");//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setHostURL
public void setQuery(String q){//sets the kind of query that is to be sent to the database
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
String s="select * from Product";//a variable that causes all the data that is in the product table to be displayed in a JTable, which also means that all the data that is in both the member and rental tables can also be displayed in a JTable
try{
ResultSet rs=statement.executeQuery(q);//an interface that is used to generate a database result set by executing a statement that queries the database
ResultSetMetaData meta=rs.getMetaData();//an interface that is used to get information about the types and properties of the columns in a ResultSet object
colCount=meta.getColumnCount();//Returns the number of columns in this ResultSet object
headers=new String[colCount];//gets the name of each column in the three tables
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);//Get the designated column's name
}//end for
while(rs.next()){
String[] record=new String[colCount];//stores the name of each column in the three tables in memory
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);//Retrieves the value of the designated column in the current row of this ResultSet object as a String
}//end for
cache.addElement(record);//Adds the specified component to the end of this vector, increasing its size by one
}//end while
fireTableChanged(null);//Forwards the given notification event to all TableModelListeners that registered themselves as listeners for this table model
}//end try
catch(Exception e){
cache=new Vector();//constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end setQuery
public void initDB(String url){
try{
db=DriverManager.getConnection(url);//tries to create a connection with the database using the DriverManager class
statement=db.createStatement();//Creates a Statement object for sending SQL statements to the database
}//end try
catch(Exception e){
System.out.println("Could not initialize the database.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end initDB
public void closeDB(){
try{
if(statement!=null){
statement.close();//Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed
}//end if
if(db!=null){
db.close();//Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released
}//end if
}//end try
catch(Exception e){
System.out.println("Could not close the current connection.");//an error message
e.printStackTrace();//a Throwable method that prints this throwable and it's backtrace to the standard error stream
}//end catch
}//end closeDB
}//end class QueryTableModelhere's an uncommented version of the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.JOptionPane;
import java.sql.*;
public class Demo extends JFrame{
static String url = "jdbc:odbc:VideoLibrary";
static Statement stmt;
static Connection con;
JTextField hostField;
JTextField queryField;
QueryTableModel qtm;
JComboBox comboBox;
public static void main(String args[]){
int choice=-1;
do{
choice=getChoice();
if(choice!=0){
getSelected(choice);
}while(choice!=5);
System.exit(0);
public static int getChoice(){
String choice;
int ch;
choice = JOptionPane.showInputDialog(null,"1. Maintain product details\n"+"2. Maintain member details\n"+"3. Maintain rental details\n"+"4. View product, member and rental details\n"+"5. Log Off\n\n"+"Enter your choice");
ch = Integer.parseInt(choice);
return ch;
public static void getSelected(int choice){
if(choice==1){
maintainProductDetails();
if(choice==2){
maintainMemberDetails();
if(choice==3){
maintainRentalDetails();
if(choice==4){
Demo test = new Demo();
test.setVisible(true);
public static Connection getConnection(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(java.lang.ClassNotFoundException e){
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
try {
con=DriverManager.getConnection(url,"","");
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
return con;
public static void maintainProductDetails(){
Connection con = getConnection();
String addProduct1, addProduct2, addProduct3, addProduct4, addProduct5, addProduct6, addProduct7, addProduct8, addProduct9, addProduct10;
addProduct1 = "insert into Product values (110001, 'The Killers - Sams Town', 5.00, 'G', 'CD', 2006)";
addProduct2 = "insert into Product values (110002, 'Robbie Williams - Rudebox', 5.00, 'G', 'CD', 2006)";
addProduct3 = "insert into Product values (110003, 'Razorlight - Razorlight', 5.00, 'G', 'CD', 2006)";
addProduct4 = "insert into Product values (110004, 'My Chemical Romance - The Black Parade', 5.00, 'G', 'CD', 2006)";
addProduct5 = "insert into Product values (110005, 'Snow Patrol - Eyes Open', 5.00, 'G', 'CD', 2006)";
addProduct6 = "insert into Product values (110006, 'Scissor Sisters - Ta-Dah!', 5.00, 'G', 'CD', 2006)";
addProduct7 = "insert into Product values (110007, 'Lovesounds - Justin Timberlake', 5.00, 'G', 'CD', 2006)";
addProduct8 = "insert into Product values (110008, 'Director - We thrive on big cities', 5.00, 'G', 'CD', 2006)";
addProduct9 = "insert into Product values (110009, 'Roxette - Roxette hits', 5.00, 'G', 'CD', 2006)";
addProduct10 = "insert into Product values (110010, '***** Cat Dolls - PCD', 5.00, 'G', 'CD', 2006)";
try {
stmt = con.createStatement();
stmt.executeUpdate(addProduct1);
stmt.executeUpdate(addProduct2);
stmt.executeUpdate(addProduct3);
stmt.executeUpdate(addProduct4);
stmt.executeUpdate(addProduct5);
stmt.executeUpdate(addProduct6);
stmt.executeUpdate(addProduct7);
stmt.executeUpdate(addProduct8);
stmt.executeUpdate(addProduct9);
stmt.executeUpdate(addProduct10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainMemberDetails(){
Connection con = getConnection();
String addMember1, addMember2, addMember3, addMember4, addMember5, addMember6, addMember7, addMember8, addMember9, addMember10;
addMember1 = "insert into Member values (1234, 'Ann', 'Smyth', 'Upper Killult, Falcarragh, Co. Donegal', '(074)-9135210', '(087)-2030172', #5/11/85#, #5/12/06#)";
addMember2 = "insert into Member values (2345, 'John', 'Murphy', 'Lower Killult, Falcarragh, Co. Donegal', '(074)-9135211', '(087)-2030173', #4/12/85#, #6/13/06#)";
addMember3 = "insert into Member values (1324, 'James', 'McFadden', 'Lower Ardsbeg, Gortahork, Co. Donegal', '(074)-9165314', '(087)-2030171', #4/11/85#, #6/14/06#)";
addMember4 = "insert into Member values (1235, 'Frankie', 'Ferry', 'Ardsmore, Gortahork, Co. Donegal', '(074)-9165325', '(087)-2031234', #6/13/60#, #6/15/06#)";
addMember5 = "insert into Member values (1236, 'Daniel', 'McKimm', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135212', '(087)-2030184', #5/14/73#, #6/16/06#)";
addMember6 = "insert into Member values (2346, 'Stephen', 'Doohan', 'Ballyness, Falcarragh, Co. Donegal', '(074)-9135213', '(087)-2030185', #6/13/85#, #5/13/06#)";
addMember7 = "insert into Member values (2347, 'James', 'Ferry', 'Meenlaragh, Gortahork, Co.Donegal', '(074)-9165360', '(087)-2031345', #9/12/85#, #5/14/06#)";
addMember8 = "insert into Member values (2348, 'Liam', 'Cannon', 'Derryconner, Gortahork, Co.Donegal', '(074)-9165324', '(087)-2031456', #4/11/86#, #5/15/06#)";
addMember9 = "insert into Member values (2401, 'Ciaran', 'Ferry', 'Brinalack, Gweedore, Co.Donegal', '(074)-9176425', '(087)-2030282', #9/12/85#, #5/16/06#)";
addMember10 = "insert into Member values (2402, 'Ciaran', 'McGee', 'Derrybeg, Gweedore, Co.Donegal', '(074)-9176536', '(087)-2030393', #9/14/85#, #5/18/06#)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addMember1);
stmt.executeUpdate(addMember2);
stmt.executeUpdate(addMember3);
stmt.executeUpdate(addMember4);
stmt.executeUpdate(addMember5);
stmt.executeUpdate(addMember6);
stmt.executeUpdate(addMember7);
stmt.executeUpdate(addMember8);
stmt.executeUpdate(addMember9);
stmt.executeUpdate(addMember10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public static void maintainRentalDetails(){
Connection con = getConnection();
String addRental1, addRental2, addRental3, addRental4, addRental5, addRental6, addRental7, addRental8, addRental9, addRental10;
addRental1 = "insert into Rental values (110001, 'The Killers - Sams Town', 1234, 'Ann', 'Smyth', #9/01/06#, #9/10/06#, 'Yes', 2.00)";
addRental2 = "insert into Rental values (120001, 'Mission Impossible 3', 2345, 'John', 'Murphy', #9/02/06#, #9/09/06#, 'No', 0.00)";
addRental3 = "insert into Rental values (130001, 'Need for Special Carbon', 1324, 'James', 'McFadden', #9/03/06#, #9/12/06#, 'Yes', 2.00)";
addRental4 = "insert into Rental values (110002, 'Robbie Williams - Rudebox', 1235, 'Frankie', 'Ferry', #9/04/06#, #9/11/06#, 'No', 0.00)";
addRental5 = "insert into Rental values (120015, 'Prime', 1236, 'Daniel', 'McKimm', #9/05/06#, #9/14/06#, 'Yes', 2.00)";
addRental6 = "insert into Rental values (130015, 'FIFA 07', 2346, 'Stephen', 'Doohan', #9/06/06#, #9/13/06#, 'No', 0.00)";
addRental7 = "insert into Rental values (110009, 'Roxette - Roxette hits', 2347, 'James', 'Ferry', #9/07/06#, #9/16/06#, 'Yes', 2.00)";
addRental8 = "insert into Rental values (120003, 'The Break Up', 2348, 'Liam', 'Cannon', #9/08/06#, #9/15/06#, 'No', 0.00)";
addRental9 = "insert into Rental values (130027, 'Gears of War', 2401, 'Ciaran', 'Ferry', #9/09/06#, #9/18/06#, 'Yes', 2.00)";
addRental10 = "insert into Rental values (110021, 'Scooter - Mind the Gap', 2402, 'Ciaran', 'McGee', #9/10/06#, #9/17/06#, 'No', 0.00)";
try{
stmt = con.createStatement();
stmt.executeUpdate(addRental1);
stmt.executeUpdate(addRental2);
stmt.executeUpdate(addRental3);
stmt.executeUpdate(addRental4);
stmt.executeUpdate(addRental5);
stmt.executeUpdate(addRental6);
stmt.executeUpdate(addRental7);
stmt.executeUpdate(addRental8);
stmt.executeUpdate(addRental9);
stmt.executeUpdate(addRental10);
stmt.close();
con.close();
catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
public Demo(){
super("Demo Test Frame");
setSize(350, 200);
comboBox = new JComboBox();
comboBox.addItem("jdbc:odbc:VideoLibrary");
qtm = new QueryTableModel();
JTable table = new JTable(qtm);
JScrollPane scrollpane = new JScrollPane(table);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
p1.add(comboBox);
p1.add(new JLabel("Enter your query: "));
p1.add(queryField = new JTextField());
p1.add(new JLabel("Click here to send: "));
JButton jb = new JButton("Search");
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
qtm.setHostURL();
qtm.setQuery(queryField.getText().trim());
p1.add(jb);
getContentPane().add(p1, BorderLayout.NORTH);
getContentPane().add(scrollpane, BorderLayout.CENTER);
import java.sql.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
public class QueryTableModel extends AbstractTableModel{
Vector cache;
int colCount;
String[] headers;
Connection db;
Statement statement;
String currentURL;
public QueryTableModel(){
cache=new Vector();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(Exception e){
System.out.println("problem loading the driver ");
public String getColumnName(int i){
return headers;
public int getColumnCount(){
return colCount;
public int getRowCount(){
return cache.size();
public Object getValueAt(int row, int col){
return ((String[])cache.elementAt(row))[col];
public void setHostURL(){
String url = "jdbc:odbc:VideoLibrary";
closeDB();
try{
db=DriverManager.getConnection(url,"","");
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void setQuery(String q){
cache=new Vector();
String s="select * from Product";
try{
ResultSet rs=statement.executeQuery(q);
ResultSetMetaData meta=rs.getMetaData();
colCount=meta.getColumnCount();
headers=new String[colCount];
for(int h=1;h<=colCount;h++){
headers[h-1]=meta.getColumnName(h);
while(rs.next()){
String[] record=new String[colCount];
for(int i=0;i<colCount;i++){
record[i]=rs.getString(i+1);
cache.addElement(record);
fireTableChanged(null);
catch(Exception e){
cache=new Vector();
e.printStackTrace();
public void initDB(String url){
try{
db=DriverManager.getConnection(url);
statement=db.createStatement();
catch(Exception e){
System.out.println("Could not initialize the database.");
e.printStackTrace();
public void closeDB(){
try{
if(statement!=null){
statement.close();
if(db!=null){
db.close();
catch(Exception e){
System.out.println("Could not close the current connection.");
e.printStackTrace(); -
Using sql:variable in an insert statement
I'm writing an insert statement for a table with an XML column. Most of the XML is static, but I need to replace the value of an element with the value of a T-SQL variable, as shown here:
CREATE TABLE [dbo].[OrderDetail](
[OrderID] [int] NULL,
[OrderDetail] [xml] NULL
GO
DECLARE @XMLData XML;
DECLARE @ItemID INT;
SET @ItemID = 1000;
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</OrderDetail>
SET @XMLData.modify('insert <ItemID>[sql:variable("@ItemID")]</ItemID> into (/OrderDetail)[1]')
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@ItemID, @XMLData);
When I run this, it inserts "[sql:variable("@ItemID")]" instead of the value of @ItemID. If someone could show me the proper syntax, I would really appreciate it. Thanks.Yes, that worked. Now I want to change it a little. I also have an attribute that I need to update with the value of a variable.
DECLARE @XMLData XML;
DECLARE @SetID INT;
DECLARE @SetIDStr VARCHAR(12);
DECLARE @SetIDXML XML;
SET @SetID = 9999;
SET @SetIDStr = CONVERT(VARCHAR(12), @SetID);
SET @SetIDXML = CONVERT(XML, @SetIDStr);
SELECT @XMLData = N'
<OrderDetail xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ItemID>1000</ItemID>
<RightOperand ID="15524" Name="ItemName" Value="15524" />
</OrderDetail>
SET @XMLData.modify('replace value of (/OrderDetail/RightOperand/@ID)[1] with sql:variable("@SetIDXML")');
INSERT INTO [dbo].[OrderDetail] ([OrderID], [OrderDetail])
VALUES (@SetID, @XMLData);
SELECT * FROM [dbo].[OrderDetail];
I'm trying to replace "ID="15524"" with the value of @SetID. This code throws an exception:
Msg 9342, Level 16, State 1, Line 23
XQuery [modify()]: An XML instance is only supported as the direct source of an insert using sql:column/sql:variable.
Thanks again for your help.
Maybe you are looking for
-
I have a problem with Illustrator CC. I have a file with spot colours in it. I have converted these spot colours to CMYK, but I still cannot save the file as a PDF-X. An error message continues to pop up saying I have spot colours somewhere, but I ha
-
Null Pointer Exception when invoking Database Adapter
The error reads as follows <2008-06-27 11:34:02,558> <ERROR> <p1.collaxa.cube.ws> <AdapterFramework::Outbound> file:/u01/app/oracle/product/10.1.3/as_mid_2/bpel/domains/p1/tmp/.bpel_UpdateA_8.2_8821b67fbd12f5dd2a0d57af136ec99e.tmp/InsertA.wsdl [ Inse
-
Magic mouse problems with windows 7
I connect the magic mouse to the computer, I can right click and left click. but it's not doing other stuff!!!!!!! Hopes help
-
T42 resolution - set to 1400x1050 without panning.
I have a need to set my resolution to 1400x1050, so i installed the driver updates http://www-307.ibm.com/pc/support/site.wss/MIGR-41918.html which talks about the feature given below: (New) The external monitor resolution can be set to 1400x1050 wit
-
I'm trying to access the SQL server 7.0 through JDBC to retreive the content of our weekly news article.I have couple of questions regarding that .. 1.We are receiving junk characters( a square box) for the special characters in the content of the ar