Insert Statement in ABAP
Hi,
I am new to ABAP Programming., i had created a function module with 5 import parameters enableing
optional and pass value options. I need to insert values to database. But function module contains only
the following statemet.
FUNCTION ZEMP_CREATE_NAME.
""Local Interface:
*" IMPORTING
*" VALUE(EMPID) TYPE ZEMPID OPTIONAL
*" VALUE(NAME1) TYPE ZNAME1 OPTIONAL
*" VALUE(ORT01) TYPE ORT01_GP OPTIONAL
*" VALUE(REGIO) TYPE REGIO OPTIONAL
*" VALUE(TELF1) TYPE TELF1 OPTIONAL
*" VALUE(STATUS) TYPE ZSTATUS OPTIONAL
*" VALUE(EPOSITION) TYPE ZPOSI OPTIONAL
insert into zemptable values('EMPID','NAME1','ORT01','REGIO','TELF1','ZSTATUS','ZPOSI')).
ENDFUNCTION.
Is this statement correct? Could someone guide me how to resolve this?
Thanks & Regards
Vijay
Check the F1 help for insert.
If you already Checked the program you know it's not right.
That looks ok for Standard SQL, but ABAP uses a special set of sql commands called open sql.
*edit
Sorry, didn't saw you were new at this, you don't want to pass that many parameters.
IF those 7 parameters make up the whole table is better to do either something like...
w_zemptable type zemptable in the importing parameters and then in the code just do
insert into zemptable values w_zemtables.
.... or better
in the tables section declare
i_zemptable like zemptable
and in the code
insert zemptable from table i_zemptable.
Edited by: Ramiro Escamilla on May 9, 2008 3:23 PM
Similar Messages
-
Dear Gurrus,
i am having a trouble in using oracle merge statement in abap, the moment i use where clause in the bottom it gives me an oracle error
EXEC SQL.
MERGE INTO SAP_GL_ACCOUNT@GETZDB a
USING SKA1 b
ON (A.gl_code= B.SAKNR)
WHEN MATCHED THEN
UPDATE SET a.posting_block = B.XSPEB,
a.locked = B.XSPEA,
A.BALANCE_SHEET = B.XBILK
WHEN NOT MATCHED THEN
insert (gl_code,
DESCRIPTION,
posting_block,
locked,
balance_sheet)
VALUES (b.SAKNR,'shadab',B.XSPEB,B.XSPEA,B.XBILK)
where b. mandt = 950 I am talking about this line
ENDEXEC.
the Moment i include WHERE clause in the botton before ENDEXEC it generates as error
" Database error text........: "ORA-00904: "A3"."MANDT": invalid identifier#ORA-02063: preceding line from GETZDB".
although its a basic feature of Oracle to inclue where clauses in insert or update in merge, but here it is generating an error.Hello Shadab,
As per my understanding of this oracle native sql code.
everything is fine except the use of direct value i.e 950 .
System is not able to process this value .
This normally happens even in normal abap sql statements also.
The better solution could be to declare a variable with the
same data type as "mandt" and then pass this "950" value into that
variable and then use this variable in the where clause instead of directly
passing the value.
i.e data:l_var type mandt vlaue '950'.
The other option could be to use the same hard coded
value but use this value in the where clause in quotations i.e.,
'950' instead of 950.
I hope this would solve your purpose, If not please reply me back.
thanks,
M.Naveen Kumar. -
Hi all
I had problem in insert statement.
I know the column of the table, tablename and the value to be insert.
My code:
Data: column(20) type c. -
>refer to the tablecolumn
Data: tablename(20) type c. -
>refer to table name
Data: value(20) type c. -
>value to be insert to the column in the table
column = 'Admino'.
tablename = 'Student'.
value = '123456'.
<b>insert <column> into <tablename> values <value>.</b>
i know there something wrong with my insert statement. How to do it in abap insert code where i can put in all the parameter in the insert statement.
Anycode or sample to show. Many thank.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.
Please reward points if helpful. -
When we use INSERT statement to insert data in DB tables there is no foriegn key check or check table validations that are performed this is clearly mention by SAP in its documentation.
I am uploading lot of data from an excel sheet into the ABAP in then using the INSERT statement to put data in the tables.
Now i need to perform the check table validation . I cannot do this validation for each and every record cause it will be very demanding on the ABAP. Can anybody suggest someway of doing this validation a FM or something ?the foriegn key/check table validations are processed on dynpros, not when directly updating the database. You need to do the validations in the ABAP yourself. For example, checking company code from your excel file.
data: xt001 type t001.
select Single * from t001 into xt001
where bukrs = iupload_file-bukrs.
if sy-subrc <> 0.
* Company code was not found.
endif.
Or you can save some hits to the database, by picking up the table first before looping at your records and doing a READ TABLE statement instead.
data: it001 type table of t001 with header line.
select * into table it001 from t001.
Loop at iupload_file.
read table it001 with key bukrs = iupload_file-bukrs.
if sy-subrc <> 0.
* Company code not found
endif.
endloop.
Welcome to SDN! Please remember to award points for any helpful answers that you might receive and mark you posts as solved when solved completely. Thanks.
Regards,
Rich Heilman -
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 -
Hi...
I want to make an insert statement with a cursor, and if in the destination table exists allready a record like in start table, I would like to skip to insert that record.....and inserting the other records from the start table......
Can anyone help me?
Thanks.Why not a plain insert statement like this
insert into dest_table (col1, col2)
select col3, col4
from source_table
where not exists(select 1 from dest_table where col1=col4); -
Insert statement in when-checkbox-checked trigger doesn't work
in a when-checkbox-checked trigger, I wrote the follwing code :
IF :sunday = 'Y' THEN
msg_alert('Y','I',false);
pkg_var.v_day_count := pkg_var.v_day_count + 1;
msg_alert('1','I',false);
:schtm_skmk.day_id := '1';
msg_alert('2 ',I',false);
INSERT INTO schtm
(ROUTE_ID, DAY_ID, FLIGHT_ID)
VALUES
(:schmf.ROUTE_ID, :schtm_skmk.day_id, 1);
COMMIT;
msg_alert('end insert schtm','I',false);
END IF;
if the checkbox is checked, I assigned value '1' to day_id. Then, I want to insert a row into table SCHTM. But, the insert statement fail. The msg_alert '2' pop up. The msg_alert 'end insert schtm' does not pop up, meaning the insert statement fail. It also fail after I replace the insert statement with the exact value of the item. But if I execute this statement in SQL plus, it insert a row into the database.
What is strange here is it did work before, I successfully insert 2 rows into database. But when I test it again just a while later, it never work anymore.
Please help.
Thanks,
Shu WenIt seems that you have missed ELSE. By the way there is only one INSERT ...
-
Urgent help needed... PL/SQL Insert statement
Hi...
I need some urgent help on this project. I have a 2 column table with values that need to be inserted into another existing table which has a sequence.
This is the 2 column table:
FUND YEAR
29587 05
29587 07
Existing table:
Name Null? Type
LIST_ID NOT NULL NUMBER(6) -- This is a sequence
WEB_USER_ID NOT NULL VARCHAR2(10)
RESOURCE_TYPE NOT NULL VARCHAR2(8)
LIST_TYPE NOT NULL VARCHAR2(10)
LIST_NAME NOT NULL VARCHAR2(50)
LIST_CODE_1 NOT NULL VARCHAR2(6) -- FUND from table above
LIST_CODE_2 NOT NULL VARCHAR2(6) -- YEAR from table above
LIST_CODE_3 NOT NULL VARCHAR2(6)
LAST_UPDATED_DT NOT NULL DATE
LAST_UPDATED_BY NOT NULL VARCHAR2(10)
LIST_CODE_4 NOT NULL VARCHAR2(20)
The columns from table 1 (FUND, YEAR) correspond to columns (LIST_CODE_1, LIST_CODE_2) in table 2. The column LIST_ID is a sequence. I can put in sysdate for LAST_UPDATED_DT and my initials SN for LAST_UPDATED_BY. This is going to be for 2 unique WEB_USER_IDs which would be in the WHERE clause. I will be inserting 2200 rows for each id. A single insert statement would look like this -
INSERT INTO EXISTING_TBL (list_id,web_user_id,resource_type,list_type,list_name,list_code_1,list_code_2,list_code_3,list_code_4,last_updated_dt,last_updated_by) VALUES ('470027','WEBUSER','GL','FUNDFYF',' FUND BALANCE SUM','12010','01',' ',' ',{ts '2010-5-19 10:16:9'},'SN')
How would I do this to insert the 2200 values from my 2 column table to the existing table?
All help is greatly appreciated!!
SNHello ,
I think this will work
INSERT INTO TABLE2
LIST_ID,
WEB_USER_ID,
RESOURCE_TYPE,
LIST_TYPE,
LIST_NAME,
LIST_CODE_1,
LIST_CODE_2,
LIST_CODE_3,
LIST_CODE_4,
LAST_UPDATED_DT,
LAST_UPDATED_BY
SELECT
SEQ.NEXTVAL,
FUND,
YEAR,
<VALUE FOR RESOURCE_TYPE>,
<VALUE FOR LIST_TYPE>,
<VALUE FOR LIST_NAME>,
<VALUE FOR LIST_CODE_1>,
<VALUE FOR LIST_CODE_2>,
<VALUE FOR LIST_CODE_3>,
<VALUE FOR LIST_CODE_4>,
SYSDATE,
'SN'
FROM
TABLE1
REGARDS
Rahul Sharma -
Insert Statement Will Not Work if a user has
I am using a MySQL database to process my Java Server Page form.
Simply, I always try to see if I can process information, first, via the command line client, then thru JSP.
At the command line client I type:
I type insert into tablename (favorite_quote) VALUES
('Sleepin' in 'da house!');
That insert throws an error. SImply said, because of the bunches of single quotes... Is there any advanced statement or insert statement to solve this?
If I do this:
INSERT INTO tablename (favorite_quote) VALUES
('Java');
It adds the record perfectly normal...
I am REALLY new to Java, so any help on this issue would be great!
BTW: Part of my Java Server Pages has:
String favorite_quote =request.getParameter("favorite_quote");
"INSERT INTO tablename (favorite_quote) VALUES " +
"('"+userid+"')";
Obviously that works fine unless anybody adds a ' or " isn't or what's, etc.
I'm loving Java, I just REALLY need some help on solving this issue.
Thank you so much! Any help would BE **WONDERFUL**!String favorite_quote
te =request.getParameter("favorite_quote");
PreparedStatement ps =
= connection.prepareStatement(""INSERT INTO tablename
(favorite_quote) VALUES (?)");
ps.setString(1, "Sleepin' in 'da house!");
ps.execute();oops a small error
PreparedStatement ps = connection.prepareStatement("INSERT INTO tablename (favorite_quote) VALUES (?)"); -
Insert statement does not insert all records from a partitioned table
Hi
I need to insert records in to a table from a partitioned table.I set up a job and to my surprise i found that the insert statement is not inserting all the records on the partitioned table.
for example when i am using select statement on to a partitioned table
it gives me 400 records but when i insert it gives me only 100 records.
can anyone help in this matter.INSERT INTO TABLENAME(COLUMNS)
(SELECT *
FROM SCHEMA1.TABLENAME1
JOIN SCHEMA2.TABLENAME2a
ON CONDITION
JOIN SCHEMA2.TABLENAME2 b
ON CONDITION AND CONDITION
WHERE CONDITION
AND CONDITION
AND CONDITION
AND CONDITION
AND (CONDITION
HAVING SUM(COLUMN) > 0
GROUP BY COLUMNS -
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(); -
Issu for running insert statement in oracle procedure.
Hi expert,
I ran a oracle procedure with a insert statement inside as:
insert into table1 select....
but I got error message related to this insert statement as "SQLERRM= ORA-08103: object no longer exists"
I ran this statement separately in toad, no error message, but no data result from this execute.
please tell how to fix this issue.
Many Thanks,
Edited by: 918440 on 27-Jun-2012 8:04 AMHi friend,
my insert statement is as follows:
INSERT INTO HIROC_RU_FACT_S
select
pp.policy_fk,
pp.transaction_log_fk,
p.policy_no,
p.policy_type_code,
hiroc_rpt_user.hiroc_get_entity_name(pp.policy_fk,'POLHOLDER') policy_holder,
pp.risk_fk,
r.risk_base_record_fk,
r.entity_fk,
hiroc_sel_entity_risk_name2 (pp.risk_fk,r.entity_fk) risk_name,
substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2) rating_state_code,
hiroc_get_province_name(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2), 'PROVINCE_CODE', 'L') rating_state_name,
hiroc_get_provicne_pol_prefix(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2),p.policy_type_code) rating_prov_pol_prefix,
nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) rating_peer_group_code,
hiroc_get_lookup_desc('PEER_GROUP',nvl(r.risk_cls_used_to_rate,pth.peer_groups_code),'L') rating_peer_group_name,
pth.policy_term_history_pk,
pth.term_base_record_fk,
to_char(pth.effective_from_date,'yyyy') term_effective_year,
c.coverage_pk,
c.coverage_base_record_fk,
pc.coverage_code,
c.product_coverage_code,
pc.long_description,
pp.coverage_component_code,
c.effective_from_date,
c.effective_to_date,
cls.coverage_code coverage_class_code,
cls.coverage_long_desc coverage_class_long_desc,
decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null) exposure_unit, --hiroc_get_expos_units_by_cov(c.coverage_pk,pc.coverage_code,c.effective_from_date,c.effective_to_date) exposure_unit,
decode(pp.coverage_component_code ,'GROSS',cls.number_of_patient_day,null) number_of_patient_day,
pth.effective_from_date term_eff_from_date,
pth.effective_to_date term_eff_to_date,
pp.premium_amount premium_amount,
(case when (pc.coverage_code in ('CP','MC1','MC2','MC3','MC4','HR','F') or pc.coverage_code like 'ST%') and
pp.coverage_component_code != 'RISKMGMT' then
(nvl(pp.premium_amount,0))
else
0
end) primary_premium,
(hiroc_get_risk_units(hiroc_get_provicne_pol_prefix(substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2),p.policy_type_code)-- rating_prov_pol_prefix
,nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) -- rating_peer_group_code
,cls.coverage_code --coverage_class_code
,decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null)
,pp.premium_amount
,(case when (pc.coverage_code in ('CP','MC1','MC2','MC3','MC4','HR','F') or pc.coverage_code like 'ST%') and
pp.coverage_component_code != 'RISKMGMT' then
(nvl(pp.premium_amount,0))
else
0
end) -- primary_premium
,p.policy_type_code
,trunc(pth.effective_to_date))) risk_units
from proddw_mart.rmv_territory_makeup tm,
proddw_mart.rmv_premium_class_makeup pcm,
proddw_mart.rmv_product_coverage pc,
proddw_mart.rmv_coverage c,
proddw_mart.rmv_risk r,
proddw_mart.rmv_policy_term_history pth,
proddw_mart.rmv_policy p,
proddw_mart.rmv_transaction_log tl,
proddw_mart.rmv_policy_premium pp,
(select /* +rule */
p.policy_no,
p.policy_start_date,
p.policy_end_date,
r.risk_pk,
r.risk_description,
c.coverage_pk,
c.parent_coverage_base_record_fk,
pc.parent_product_covg_code,
pc.coverage_code,
pc.short_description coverage_short_desc,
pc.long_description coverage_long_desc,
c.exposure_unit,
pc.exposure_basis_code,
c.number_of_patient_day,
p.policy_start_date policy_effective_date,
p.policy_end_date policy_expiry_date,
c.effective_from_date,
c.effective_to_date,
to_char(c.effective_from_date,'YYYY') class_eff_year
from proddw_mart.odwr_coverage_only c
,proddw_mart.odwr_product_coverage pc
,proddw_mart.odwr_risk r
,proddw_mart.odwr_policy p
where pc.code = c.product_coverage_code
and pc.parent_product_covg_code is not null -- coverage classes only
and r.risk_pk = c.risk_base_record_fk
and c.accounting_to_date = to_date('1/1/3000','mm/dd/yyyy') -- only open records
and c.base_record_b = 'N'
and p.base_record_b = 'N'
and p.policy_pk = r.policy_fk
and p.accounting_to_date = to_date('1/1/3000','mm/dd/yyyy') -- only open records
group by p.policy_no,
p.policy_start_date,
p.policy_end_date,
r.risk_pk,
r.risk_description,
c.coverage_pk,
c.parent_coverage_base_record_fk,
pc.parent_product_covg_code,
pc.coverage_code,
pc.short_description, -- coverage_short_desc,
pc.long_description, -- coverage_long_desc,
c.exposure_unit,
pc.exposure_basis_code,
c.number_of_patient_day,
p.policy_start_date, -- policy_effective_date,
p.policy_end_date, -- policy_expiry_date,
c.effective_from_date,
c.effective_to_date,
to_char(c.effective_from_date,'YYYY')-- class_eff_year
) cls
where tm.risk_type_code = r.risk_type_code
and tm.county_code = r.county_code_used_to_rate
and tm.effective_from_date <= pp.rate_period_from_date
and tm.effective_to_date > pp.rate_period_from_date
and pcm.practice_state_code (+) = r.practice_state_code
and pcm.risk_class_code (+) = r.risk_cls_used_to_rate
and nvl(pcm.effective_from_date, pp.rate_period_from_date) <= pp.rate_period_from_date
and nvl(pcm.effective_to_date, to_date('01/01/3000','mm/dd/yyyy')) > pp.rate_period_from_date
and pc.code = c.product_coverage_code
and c.base_record_b = 'N'
and ( c.record_mode_code = 'OFFICIAL'
and (c.closing_trans_log_fk is null or
c.closing_trans_log_fk != tl.transaction_log_pk)
or c.record_mode_code = 'TEMP'
and c.transaction_log_fk = tl.transaction_log_pk )
and c.parent_coverage_base_record_fk is null
and c.effective_from_date < c.effective_to_date
and c.effective_from_date <= pp.rate_period_from_date
and c.effective_to_date > pp.rate_period_from_date
and c.accounting_from_date <= tl.accounting_date
and c.accounting_to_date > tl.accounting_date
and c.coverage_base_record_fk=pp.coverage_fk
and r.base_record_b = 'N'
and ( r.record_mode_code = 'OFFICIAL'
and (r.closing_trans_log_fk is null or
r.closing_trans_log_fk != tl.transaction_log_pk)
or r.record_mode_code = 'TEMP'
and r.transaction_log_fk = tl.transaction_log_pk )
and r.effective_from_date < r.effective_to_date
and r.effective_from_date <= pp.rate_period_from_date
and r.effective_to_date > pp.rate_period_from_date
and r.accounting_from_date <= tl.accounting_date
and r.accounting_to_date > tl.accounting_date
and r.risk_base_record_fk = pp.risk_fk
and pth.base_record_b = 'N'
and ( pth.record_mode_code = 'OFFICIAL'
and (pth.closing_trans_log_fk is null or
pth.closing_trans_log_fk != tl.transaction_log_pk)
or pth.record_mode_code = 'TEMP'
and pth.transaction_log_fk = tl.transaction_log_pk )
and pth.accounting_from_date <= tl.accounting_date
and pth.accounting_to_date > tl.accounting_date
and pth.term_base_record_fk = pp.policy_term_fk
and p.policy_pk = pp.policy_fk
and tl.transaction_log_pk = pp.transaction_log_fk
and pp.active_premium_b = 'Y'
and pp.rate_period_type_code in ('CS_PERIOD','SR_PERIOD')
and pp.rate_period_to_date > pp.rate_period_from_date
and tl.accounting_date <= sysdate
and p.policy_cycle_code = 'POLICY'
and substr(p.policy_no,1,1) <> 'Q'
and tl.transaction_log_pk = (select max(pp.transaction_log_fk)
from proddw_mart.rmv_policy_premium pp,proddw_mart.rmv_transaction_log tl2
where pth.term_base_record_fk = pp.policy_term_fk
and pp.transaction_log_fk = tl2.transaction_log_pk
and tl2.accounting_date <= sysdate )
and p.policy_type_code in ('LIABCRIME','MIDWIFE')
and pth.accounting_to_date = to_date('01/01/3000','mm/dd/yyyy') --<<<******* eliminates duplicates
and p.policy_no = cls.policy_no
-- and r.risk_pk = cls.risk_pk
and c.coverage_base_record_fk = cls.parent_coverage_base_record_fk(+)
and cls.effective_from_date < pth.effective_to_date -- from date less than period end date
and cls.effective_to_date > pth.effective_from_date -- to date greater than period start date
and cls.policy_effective_date < pth.effective_to_date -- from date less than period end date
and cls.policy_expiry_date > pth.effective_from_date -- to date greater than period start date
group by pp.policy_fk,
pp.transaction_log_fk,
p.policy_no,
p.policy_type_code,
pp.risk_fk,
r.risk_base_record_fk,
r.entity_fk,
substr(trim(nvl(r.county_code_used_to_rate,pth.issue_state_code)),1,2), -- rating_state_code,
r.county_code_used_to_rate,
pth.issue_state_code,
nvl(r.risk_cls_used_to_rate,pth.peer_groups_code) , -- rating_peer_group_code,
r.risk_cls_used_to_rate,
pth.peer_groups_code,
pth.policy_term_history_pk,
pth.term_base_record_fk,
to_char(pth.effective_from_date,'yyyy'), --term_effective_year,
c.coverage_pk,
c.coverage_base_record_fk,
pc.coverage_code,
c.product_coverage_code,
pc.long_description,
pp.coverage_component_code,
c.effective_from_date,
c.effective_to_date,
cls.coverage_code, -- coverage_class_code,
cls.coverage_long_desc, -- coverage_class_long_desc,
decode(pp.coverage_component_code ,'GROSS',cls.exposure_unit,null),-- exposure_unit,
decode(pp.coverage_component_code ,'GROSS',cls.number_of_patient_day,null), -- number_of_patient_day,
pth.effective_from_date, --term_eff_from_date,
pth.effective_to_date, --, --term_eff_to_date,
pp.premium_amount ;Edited by: BluShadow on 27-Jun-2012 16:12
added {noformat}{noformat} tags for readability. PLEASE READ {message:id=9360002} AS PREVIOUSLY REQUESTED! & -
VLD-1119: Unable to generate Multi-table Insert statement for some or all t
Hi All -
I have a map in OWB 10.2.0.4 which is ending with following error: -
VLD-1119: Unable to generate Multi-table Insert statement for some or all targets.*
Multi-table insert statement cannot be generated for some or all of the targets due to upstream graphs of those targets are not identical on "active operators" such as "join".*
The map is created with following logic in mind. Let me know if you need more info. Any directions are highly appreciated and many thanks for your inputs in advance: -
I have two source tables say T1 and T2. There are full outer joined in a joiner and output of this joined is passed to an expression to evaluate values of columns based on
business logic i.e. If T1 is available than take T1.C1 else take T2.C1 so on.
A flag is also evaluated in the expression because these intermediate results needs to be joined to third source table say T3 with different condition.
Based on value taken a flag is being set in the expression which is used in a splitter to get results in three intermediate tables based on flag value evaluated earlier.
These three intermediate tables are all truncate insert and these are unioned to fill a final target table.
Visually it is something like this: -
T1 -- T3 -- JOINER1
| -->Join1 (FULL OUTER) --> Expression -->SPLITTER -- JOINER2 UNION --> Target Table
| JOINER3
T2 --
Please suggest.I verified that their is a limitation with the splitter operator which will not let you generate a multi split having more than 999 columns in all.
I had to use two separate splitters to achieve what I was trying to do.
So the situation is now: -
Siource -> Split -> Split 1 -> Insert into table -> Union1---------Final tableA
Siource -> Split -> Split 2 -> Insert into table -> Union1 -
Generate Insert Statement Script to Extract Data from Table in Oracle 7i
Hi all, I have an old Oracle legacy system that is running for over 15 years.Every now and then we need to extract data from this table@ ORacle 7i to be imported back to Oracle 10G.
My thoughts are to create a script of Insert statements in oracle 7 and that to be deployed back to Oracle 10G.
I found this scripts in Google and not sure how exactly this works.Any explanation on thsi scripts , would be greatly appreciated.I find this scripst may help to generate a set of insert statements from that table to the latest table at 10G.
<pre>
-- Step 1: Create this procedure:
create or replace Function ExtractData(v_table_name varchar2) return varchar2 As
b_found boolean:=false;
v_tempa varchar2(8000);
v_tempb varchar2(8000);
v_tempc varchar2(255);
begin
for tab_rec in (select table_name from user_tables where table_name=upper(v_table_name))
loop
b_found:=true;
v_tempa:='select ''insert into '||tab_rec.table_name||' (';
for col_rec in (select * from user_tab_columns
where
table_name=tab_rec.table_name
order by
column_id)
loop
if col_rec.column_id=1 then
v_tempa:=v_tempa||'''||chr(10)||''';
else
v_tempa:=v_tempa||',''||chr(10)||''';
v_tempb:=v_tempb||',''||chr(10)||''';
end if;
v_tempa:=v_tempa||col_rec.column_name;
if instr(col_rec.data_type,'CHAR') > 0 then
v_tempc:='''''''''||'||col_rec.column_name||'||''''''''';
elsif instr(col_rec.data_type,'DATE') > 0 then
v_tempc:='''to_date(''''''||to_char('||col_rec.column_name||',''mm/dd/yyyy hh24:mi'')||'''''',''''mm/dd/yyyy hh24:mi'''')''';
else
v_tempc:=col_rec.column_name;
end if;
v_tempb:=v_tempb||'''||decode('||col_rec.column_name||',Null,''Null'','||v_tempc||')||''';
end loop;
v_tempa:=v_tempa||') values ('||v_tempb||');'' from '||tab_rec.table_name||';';
end loop;
if Not b_found then
v_tempa:='-- Table '||v_table_name||' not found';
else
v_tempa:=v_tempa||chr(10)||'select ''-- commit;'' from dual;';
end if;
return v_tempa;
end;
show errors
-- STEP 2: Run the following code to extract the data.
set head off
set pages 0
set trims on
set lines 2000
set feed off
set echo off
var retline varchar2(4000)
spool c:\t1.sql
select 'set echo off' from dual;
select 'spool c:\recreatedata.sql' from dual;
select 'select ''-- This data was extracted on ''||to_char(sysdate,''mm/dd/yyyy hh24:mi'') from dual;' from dual;
-- Repeat the following two lines as many times as tables you want to extract
exec :retline:=ExtractData('dept');
print :retline;
exec :retline:=ExtractData('emp');
print :retline;
select 'spool off' from dual;
spool off
@c:\t1
-- STEP3: Run the spooled output c:\recreatedata.sql to recreate data.
Source:http://www.idevelopment.info/data/Oracle/DBA_tips/PL_SQL/PLSQL_5.shtml
</pre>Thanks Justin.
I get what you are saying,i really wanted to see the output of the codes, because the furtherst i could get from that code is
SELECT EXTRACTDATA('MYTABLE') FROM MYTABLE;
and it generated this:
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
"select 'insert into MYTABLE ('||chr(10)||'DATE1,'||chr(10)||'TIME1,'||chr(10)||'COUNTS) values ('||decode(DATE1,Null,'Null','to_date('''||to_char(DATE1,'mm/dd/yyyy hh24:mi')||''',''mm/dd/yyyy hh24:mi'')')||','||chr(10)||''||decode(TIME1,Null,'Null',TIME1)||','||chr(10)||''||decode(COUNTS,Null,'Null',COUNTS)||');' from MYTABLE;
select '-- commit;' from dual;"
I was expecting a string of
insert into mytable values (19/1/2009,1,1);
insert into mytable values (19/10/2008,5,10);
Thanks for the explanation . -
Report with stored proc running multiple stored procedures with insert statement
Hi,
I wonder if this is possible in SSRS ... I use the 2012 version (Data Tools).
I have a report that triggers a stored procedure. See below.
Within this SP there are 2 insert statements getting data from 2 other SP's.
When I make a dataset referring to the main SP below, SSRS does not show me any fields at all.
Is this because it's a SP with insert statements and nested SP's?
At the end of the SP I make a select so it should see all the fields.
The parameters @month and @costcenter are multivalue params. I use a special function to convert the multivalues, selected in the report, into a string to pass it correctly to the query (comma separated).
USE [TestDB]
GO
/****** Object: StoredProcedure [dbo].[_Pink_SP_StandingsRegisterDataset] Script Date: 15-4-2014 13:31:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[_Pink_SP_StandingsRegisterDataset]
@year INT,
@month NVARCHAR(50),
@costcenter NVARCHAR(500),
@GLaccount NVARCHAR(9)
AS
BEGIN
/* Remove existing content*/
DELETE FROM _Pink_TB_StandingsRegister
/* Add records part 1 */
INSERT INTO _Pink_TB_StandingsRegister
EXEC _Pink_SP_StandingsRegister @year, @month, @costcenter, @GLaccount
/* Add records part 2 */
INSERT INTO _Pink_TB_StandingsRegister
Type,
Row,
Year,
Month,
YearDatetable,
MonthDatetable
EXEC _Pink_SP_StandingsRegisterDatetable @year
/* Select all records */
SELECT *
FROM _Pink_TB_StandingsRegister
END
GOHi bijntjede2e,
After testing a similar scenario in my own environment, it works well in Reporting Services. In my test, the stored procedure returns all the fields from _Pink_TB_StandingsRegister table in the dataset. Then I select some values from year, month, costcenter
and Glaccount parameters, it inserts some values in the _Pink_TB_StandingsRegister table. So we can use this stored procedure as the dataset in the report.
In order to solve the problem more efficiently, I need to clarify some information.
Are you pass multiple values parameter to one stored procedure correctly? We can refer to the following thread:
http://social.technet.microsoft.com/Forums/en-US/dbdfa101-cccc-4e9f-aa50-566dc5ebcc27/ssrs-2008-r2-report-dataset-call-a-stored-procedure?forum=sqlrep
What results are you get when executing the stored procedure in SQL Server Management Studio? Is it works well? We should double those stored procedures.
If there are any misunderstanding, please elaborate the issue for further investigation.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support
Maybe you are looking for
-
How can i get an itunes gift code?
hi everyone i bought a refurbish mac and i got a code to upgrade to os lion but i live in trinidad west indies and my country is not on the list, how can i redeem this upgrade?
-
Constantly having kernel panics on Macbook Pro
Hi all, For the last couple of weeks I'm having kernel panics on my MBP. The last couple of days I'm having more and more of these panics. It's starting to drive me crazy and was wondering if someone could help me with my last rapport. Is it a third
-
Not able to display the image on the popup.
hi, my requirement is: i have command link on the form.which on clicked should display a popup and with in that popup a image should be shown. I have stored that image in the form of byte array. On clicking the link i am able to show the popup.But,no
-
Flash content has dotted border after upgrading to Firefox 6.
Since upgrading to Firefox 6 (now 6.0.2), interaction (ie: using buttons) with Flash content creates a dotted border around the movie. This does not occur with Google Chrome, Safari, or even Opera. Normally, this flash-based version of my site requir
-
How do i delete third party app icon? pls help