Insert into JComboBox....
I am trying to insert another option into a JComboBox, however, I do not wish to append it. I need to insert it in between two other options. I cannot seem to find a method to do this. I know this is possible with JLists as you can specify an int and the object where the int is the position to insert. Despite searching I cannot seem to find a method that will take both and int and a object to place in the JComboBox. Any ideas would be helpful
Hi, the JComboBox class has a method called insertItemAt(). Have you tried using that yet?
(taken from the API)
====================================================================
public void insertItemAt(Object anObject, int index)
Inserts an item into the item list at a given index. This method works only if the JComboBox uses the default data model. JComboBox uses the default data model when created with the empty constructor and no other model has been set.
Parameters:
anObject - the Object to add to the list
index - an integer specifying the position at which to add the item
====================================================================
Similar Messages
-
JBO 25030 while inserting into JTab with jNavigationBar
Hello,
in a master/detail swing panel the insert button of the navigation bar for the detail view throws "JBO-25030: Failed to find or invalidate owning entity."
- The views are connected through a view link
- The Detail View is a join through several entities. These are all marked as "updatable" for the table cells are combo boxes. However I only want to insert into the table that holds the foreign key to the master view.
Help is appreciated.
Thanks
JanHello Frank,
here the testcase
- MasterView is a join through several tables, f.ex.:
select (..)from country, town
- DetailView is also joins through several tables. At the lowest level there is a m:n relationship. Ex: A road parameter says which combination of road type and road use is available.
select (...)
from road ro, roadparameter rp, roaduse ru, roadtype rt
where ro.rp_id = rp.id
and RP.ru_id = ru.id
and RP.rt_id = rt.id
- DetailView was put in a JTable and added a JuNavigationBar. In DetailView the cell RT_ID was assigned to a combobox. Changing the road type changes the selection in the road use cell(also combo box).
private JComboBox roadTypeCellEditor= new JComboBox();
roadTypeCellEditor.setModel((ComboBoxModel)panelBinding.bindUIControl("rt_id",roadTypeCellEditor));
jTable2.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(roadTypeCellEditor));
-There is a View Link between MasterView.id(town) and DetailView.town_id(road)
- While inserting with the Navigation into the DetailView Table, JBO 25030 comes up.
JDev Version : 10.1.2.0.0
Thanks ,
Jan -
How can I insert into a table other than the default table in a form
Hi,
I want to insert into a table with some fields value of a form of another table. I have written insert code On successful submission of that form, but after submit it gives the following error
An unexpected error occurred: ORA-06502: PL/SQL: numeric or value error (WWV-16016)
My code is like this
declare
l_trn_id number;
l_provider_role varchar2(3);
l_provider_id varchar2(10);
begin
l_trn_id := p_session.get_value_as_number(p_block_name=>'DEFAULT',p_attribute_name=>'A_TRANSACTION_ID');
l_provider_id := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',p_attribute_name=>'A_PROVIDER1');
l_PROVIDER_ROLE := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',p_attribute_name=>'A_PROVIDER_ROLE1');
if (l_provider_role is not null) and (l_provider_id is not null) then
insert into service_provider_trans_records(service_provider_id,transaction_id,role_type_id)
values(l_provider_id, l_trn_id, l_provider_role);
commit;
end if;
end;
Where 'PROVIDER1' and 'PROVIDER_ROLE1' are not table fields.
How can do that or why this error comes ? Any idea?
Thanks
SumitaHi,
When do you get this error? Is it while running or while creating the form.
Here is a sample code which inserts a non-database column dummy into a table called dummy. This is done in successful procedure.
declare
l_dummy varchar2(1000);
begin
l_dummy := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',
p_attribute_name=>'A_DUMMY');
insert into sjayaram903_1g.dummy values(l_dummy);commit;
end;
Please check in your case if the size of the local variable is enough to hold the values being returned.
Thanks,
Sharmila -
hi,guruvulu
this is the program...............to insert the data into sap r/3 table
but record is not inserting....any commit i have to write in my program?
Created on Feb 20, 2007
TODO To change the template for this generated file go to
Window - Preferences - Java - Code Style - Code Templates
package comm;
@author sapusr006
TODO To change the template for this generated type comment go to
Window - Preferences - Java - Code Style - Code Templates
Example2.java
Property of SAP AG, Walldorf
(c) Copyright SAP AG, Walldorf, 2000-2005.
All rights reserved.
//import java.sql.Connection;
//import java.sql.PreparedStatement;
import com.sap.mw.jco.IFunctionTemplate;
import com.sap.mw.jco.IRepository;
import com.sap.mw.jco.JCO;
@version 1.0
@author SAP AG, Walldorf
public class Fm {
// The MySAP.com system we gonna be using
static final String SID = "R3";
// static String query="insert into BAPI_COMPANYCODE_GETLIST values(?,?)";
// The repository we will be using
IRepository repository;
//ESTABLISHING A CONNECTION TO SAP
public Fm()
try {
JCO.addClientPool( SID, // Alias for this pool
10, // Max. number of connections
"800", // SAP client
"RFCTEST", // userid
"welcome", // password
"EN", // language
"10.10.88.170", // host name
"01" );
// Create a new repository
// The repository caches the function and structure definitions
// to be used for all calls to the system SID. The creation of
// redundant instances cause performance and memory waste.
repository = JCO.createRepository("MYRepository", SID);
catch (JCO.Exception ex) {
System.out.println("Caught an exception: \n" + ex);
// RETRIEVES AND DISPLAY A ZHR INFOTYPE OPERATION
public void salesOrders()
JCO.Client client = null;
try {
// Get a function template from the repository
//System.out.println("goes to sales order");
IFunctionTemplate ftemplate = repository.getFunctionTemplate("ZHR_INFOTYPE_OPERATION");
System.out.println("hai");
if(ftemplate != null) {
// Create a function from the template
JCO.Function function = ftemplate.getFunction();
JCO.ParameterList paralist=function.getImportParameterList();
paralist.setValue("0000000011","PERNR");
paralist.setValue("UPD","ACTIO");
paralist.setValue("A","TCLAS");
System.out.println("hello");
paralist.setValue("20061215","BEGDA");
System.out.println("hello");
paralist.setValue("20061215","ENDDA");
paralist.setValue("1","OBJPS");
paralist.setValue("LTA","SUBTY");
System.out.println("SETTING VALUES");
// Get a client from the pool
client = JCO.getClient(SID);
System.out.println("goes to sales order");
//function.getImportParameterList().setValue("QUERY_TABLE","ZHRJ2EETEST");
//EXECUTING THE FUNCTION
client.execute(function);
System.out.println("after exeucting the function");
// NO OF IMPORT PARAMS IT DISPLAY
//STRUCTURE
JCO.Structure returnStructure =
function.getExportParameterList().getStructure("RETURN");
String structure=returnStructure.toString();
System.out.println(structure);
JCO.Table sales_orders = function.getTableParameterList().getTable("PROPOSED_VALUES");
System.out.println("after function");
System.out.println("proposed111"+sales_orders.getNumRows());
sales_orders.firstRow();
sales_orders.appendRows(3);
sales_orders.setValue("0582","INFTY");
sales_orders.setValue("P0582-AMTEX","FNAME");
sales_orders.setValue("200.00","FVAL");
sales_orders.nextRow();
sales_orders.setValue("0582","INFTY");
sales_orders.setValue("P0582-JBGDT","FNAME");
sales_orders.setValue("20061215","FVAL");
sales_orders.nextRow();
sales_orders.setValue("0582","INFTY");
sales_orders.setValue("P0582-JENDT","FNAME");
sales_orders.setValue("20061215","FVAL");
System.out.println("proposed222"+sales_orders.getNumRows());
/*for (int i = 0; i <sales_orders.getNumRows(); i++) {
sales_orders.setRow(i);
System.out.println(sales_orders.getString("INFTY"));
JCO.Table sales_orders1 = function.getTableParameterList().getTable("MODIFIED_KEYS");
System.out.println("modified"+sales_orders1.getNumRows());
sales_orders1.setRow(1);
sales_orders1.appendRows(1);
sales_orders1.setValue("0000000011","PERNR");
sales_orders1.setValue("0582","INFTY");
sales_orders1.setValue("LTA","SUBTY");
sales_orders1.setValue("1","OBJPS");
sales_orders1.setValue("20061215","BEGDA");
sales_orders1.setValue("20061215","ENDDA");
System.out.println("modified222"+sales_orders1.getNumRows());
System.out.println("execute222"+sales_orders1.getNumRows());
for (int i = 0; i <sales_orders1.getNumRows(); i++) {
sales_orders.setRow(i);
System.out.println("hia"+sales_orders1.getString("SUBTY"));
System.out.println("NO OF ROWS ARE:---"+ sales_orders.getNumRows());
String fieldName[]=new String[sales_orders.getFieldCount()];
System.out.println("THE COLUMNS IN THE TABLE ARE:--"+sales_orders.getFieldCount());
// sales_orders.firstRow();
//COLUMNS NAMES
System.out.println(fieldName.length);
for (int iCtrst = 0;iCtrst < sales_orders1.getFieldCount();iCtrst++) {
fieldName[iCtrst] = sales_orders1.getName(iCtrst);
System.out.println(fieldName[iCtrst]);
if (sales_orders.getNumRows() > 0) {
// Loop over all rows
do {
System.out.println("----
//int r=1;
// Loop over all columns in the current row
for (JCO.FieldIterator e = sales_orders.fields(); e.hasMoreElements();)
JCO.Field field = e.nextField();
String compcode=field.getString();
//pst.setString(r,compcode);
System.out.println(field.getName() + ":\t" + field.getString());
// r++;
}//for
// i=pst.executeUpdate();
} while(sales_orders.nextRow());
else {
System.out.println("No results found");
if (sales_orders1.getNumRows() > 0) {
// Loop over all rows
do {
System.out.println("----
//int r=1;
// Loop over all columns in the current row
for (JCO.FieldIterator e = sales_orders1.fields(); e.hasMoreElements();)
JCO.Field field1 = e.nextField();
//String compcode=field1.getString();
//pst.setString(r,compcode);
System.out.println(field1.getName() + ":\t" + field1.getString());
// r++;
}//for
// i=pst.executeUpdate();
} while(sales_orders1.nextRow());
else {
System.out.println("No results found");
System.out.println("modified"+sales_orders1.getNumRows());
System.out.println("modified"+sales_orders.getNumRows());
//if
/* if(i>=1)
System.out.println("\t\t\tUpdated ORACLE successfully");
else {
System.out.println("FUNCTION MODULE not found in backend system.");
}//if
catch (JCO.AbapException ex) {
System.out.println("Caught an exception: \n" + ex);
}catch(Exception en){en.printStackTrace();}
finally {
JCO.releaseClient(client);
protected void cleanUp() {
JCO.removeClientPool(SID);
public static void main(String[] argv)
Fm e=new Fm();
// e.systemInfo();
e.salesOrders();
e.cleanUp();
output:
TABLE: MODIFIED_KEYS
TABLE: PROPOSED_VALUES
IMPORT ACTIO
IMPORT BEGDA
IMPORT DIALOG_MODE
IMPORT ENDDA
IMPORT LUW_MODE
IMPORT MASSN
IMPORT NO_ENQUEUE
IMPORT NO_EXISTENCE_CHECK
IMPORT OBJPS
IMPORT PERNR
IMPORT PERSG
IMPORT PERSK
IMPORT PLANS
IMPORT SEQNR
IMPORT SPRPS
IMPORT SUBTY
IMPORT TCLAS
IMPORT WERKS
EXPORT HR_RETURN
EXPORT RETURN
EXPORT RETURN1
appending
NO OF ROWS ARE:---3
THE COLUMNS IN THE TABLE ARE:--4
INFTY: 0582
FNAME: P0582-AMTEX
FVAL: 200.00
SEQNR: 00
INFTY: 0582
FNAME: P0582-JBGDT
FVAL: 20061215
SEQNR: 00
INFTY: 0582
FNAME: P0582-JENDT
FVAL: 20061215
SEQNR: 00
PERNR: 00000011
INFTY: 0582
SUBTY: LTA
OBJPS: 1
SPRPS:
ENDDA: 2006-12-15
BEGDA: 2006-12-15
SEQNR: 000hi jagadesh,
ur code is very length to see.
see the following code ,
JCO.Function objFunction =
this
.objIRepository
.getFunctionTemplate("BAPI_MATERIAL_AVAILABILITY")
.getFunction();
objFunction.getImportParameterList().setValue(strPlant, "PLANT");
objFunction.getImportParameterList().setValue(strMaterial, "MATERIAL");
objFunction.getImportParameterList().setValue(strQuantity, "UNIT");
this.objClient.execute(objFunction);
JCO.Structure ret =
objFunction.getExportParameterList().getStructure("RETURN");
String strRetMsg = ret.getString("MESSAGE");
System.out.println(strRetMsg); // it will tell whether record is inserted or not
/*JCO.Function objFunction1 =
this
.objIRepository
.getFunctionTemplate("BAPI_TRANSACTION_COMMIT")
.getFunction();
objFunction1.setValue("",WAIT);
objClient.execute(objFunction1);*/
CHECK THE RETURN MSG .IT WILL TELL THE PROBLEM
give me points if it is useful
regards
Guru
Message was edited by:
Guruvulu Bojja
Message was edited by:
Guruvulu Bojja
Message was edited by:
Guruvulu Bojja -
Best Practice to fetch SQL Server data and Insert into Oracle Tables
Hello,
I want to read sqlserver data everry half an hour and write into oracle tables ( in two different databases). What is the best practice for doing this?
We do not have any database dblinks from oracle to sqlserver and vice versa.
Any help is highly appreciable?
ThanksWell, that's easy:
use a TimerTask to do the following every half an hour:
- open a connection to sql server
- open two connections to the oracle databases
- for each row you read from the sql server, do the inserts into the oracle databases
- commit
- close all connections -
Splitting data in one row and inserting into seperate rows into a new table
i have a table table1 like the following
column1 column2 column3
a b,cbdm,d hj
ba hello man
i have to insert data from this table to table2 in the following format
Column1 column2 column3
a b hj
a cbdm hj
a d hj
ba hello man
It is like if data in column2 is seperated by comma i have to insert it into each sperate row
I have to write a single procedure which will do the above. Please,Please help me
I am very new to SQLI am absolutely agreeing with Billy.
But I think u will be able to learn a lot if u try to understand the following code
sql>select * from t1;
C1 C2 C3
a b,cdbm,d hj
ba hello man
x aa,d,df yy
sql>select * from t2;
no rows selected
sql>insert into t2
select col1,col2,col3
from (
select t1.c1 col1,t1.c2 col4,t1.c3 col3,
substr(t1.c2,
case n when 1 then 1 else instr(t1.c2,',',1,n-1)+1 end,
(case instr(t1.c2,',',1,n) when 0 then length(t1.c2)+1 else instr(t1.c2,',',1,n) end) -
(case n when 1 then 1 else instr(t1.c2,',',1,n-1)+1 end)) col2,n
from t1,(select c1,c2,c3,
row_number() over(partition by c1,c2,c3 order by c1) n
from t1 connect by level <=
(length(t1.c2)-length(replace(t1.c2,',','')))) t2
where t1.c1 = t2.c1)
where not(n != 1 and col4=col2);
sql>select * from t2;
C1 C2 C3
a b hj
a cdbm hj
a d hj
ba hello man
x aa yy
x d yy
x df yy -
Inserting into a table which is created "on the fly" from a trigger
Hello all,
I am trying to insert into a table from a trigger in Oracle form. The table name however, is inputted by the user in am item form.
here is what the insert looks like:
insert into :table_name
values (:value1, :value2);
the problem is that forms does not recognize ::table_name. If I replace :table_name with an actual database table, it works fine. However, I need to insert to a table_name based from oracle form item.
By the way, the table|_name is built on the fly using a procedure before I try to insert into it.
Any suggestion on how can I do that? My code in the trigger is:
declare
dm_drop_tbl(:table_name,'table) // a call to an external procedure to drop the table
dm_create_tbl(:table_name,'att1','att2');
insert into :table_name
values (:value1, :value2);
this give me an error:
encounter "" when the symbol expecting one.....Hi ,
You should use the FORMS_DDL built_in procedure. Read the on-line documentation of forms ...
Simon -
Problem while inserting into a table which has ManyToOne relation
Problem while inserting into a table *(Files)* which has ManyToOne relation with another table *(Folder)* involving a attribute both in primary key as well as in foreign key in JPA 1.0.
Relevent Code
Entities:
public class Files implements Serializable {
@EmbeddedId
protected FilesPK filesPK;
private String filename;
@JoinColumns({
@JoinColumn(name = "folder_id", referencedColumnName = "folder_id"),
@JoinColumn(name = "uid", referencedColumnName = "uid", insertable = false, updatable = false)})
@ManyToOne(optional = false)
private Folders folders;
public class FilesPK implements Serializable {
private int fileId;
private int uid;
public class Folders implements Serializable {
@EmbeddedId
protected FoldersPK foldersPK;
private String folderName;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "folders")
private Collection<Files> filesCollection;
@JoinColumn(name = "uid", referencedColumnName = "uid", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Users users;
public class FoldersPK implements Serializable {
private int folderId;
private int uid;
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer uid;
private String username;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "users")
private Collection<Folders> foldersCollection;
I left out @Basic & @Column annotations for sake of less code.
EJB method
public void insertFile(String fileName, int folderID, int uid){
FilesPK pk = new FilesPK();
pk.setUid(uid);
Files file = new Files();
file.setFilename(fileName);
file.setFilesPK(pk);
FoldersPK folderPk = new FoldersPK(folderID, uid);
// My understanding that it should automatically handle folderId in files table,
// but it is not…
file.setFolders(em.find(Folders.class, folderPk));
em.persist(file);
It is giving error:
Internal Exception: java.sql.SQLException: Field 'folderid' doesn't have a default value_
Error Code: 1364
Call: INSERT INTO files (filename, uid, fileid) VALUES (?, ?, ?)_
_ bind => [hello.txt, 1, 0]_
It is not even considering folderId while inserting into db.
However it works fine when I add folderId variable in Files entity and changed insertFile like this:
public void insertFile(String fileName, int folderID, int uid){
FilesPK pk = new FilesPK();
pk.setUid(uid);
Files file = new Files();
file.setFilename(fileName);
file.setFilesPK(pk);
file.setFolderId(folderId) // added line
FoldersPK folderPk = new FoldersPK(folderID, uid);
file.setFolders(em.find(Folders.class, folderPk));
em.persist(file);
My question is that is this behavior expected or it is a bug.
Is it required to add "column_name" variable separately even when an entity has reference to ManyToOne mapping foreign Entity ?
I used Mysql 5.1 for database, then generate entities using toplink, JPA 1.0, glassfish v2.1.
I've also tested this using eclipselink and got same error.
Please provide some pointers.
ThanksHello,
What version of EclipseLink did you try? This looks like bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280436 that was fixed in EclipseLink 2.0, so please try a later version.
You can also try working around the problem by making both fields writable through the reference mapping.
Best Regards,
Chris -
Hallo,
We have the problem that subscriptions cannot be sent. In defaultTrace I have found following entry:
#1.5 #32B150008004002400001641000710B80004539FE52B4274#1217846116565#com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionsOpenSQL#sap.com/irj#com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionsOpenSQL#LI01736#118449##iscp63.isc.aok.de_LFP_399377450#LI01736#03186780621111ddb4c432b150008004#SAPEngine_Application_Thread[impl:3]_10##0#0#Fatal##Plain###Cannot unsubscribe user. Context: ResourceContext: user=LI01736, creationTime=1217846116420, locale=de. User: LI01736. ID: 50cdd784-51ac-2810-2393-ea9709f50de3. Recipient: com.sapportals.wcm.util.channels.wcm.Recipient@ce9b7f70. Step: Executing SQL INSERT. . Trying to rollback transaction.#
#1.5 #32B150008004002400001643000710B80004539FE52B989A#1217846116586#com.sap.sql.jdbc.common.StatementAnalyzerImpl#sap.com/irj#com.sap.sql.jdbc.common.StatementAnalyzerImpl#LI01736#118449##iscp63.isc.aok.de_LFP_399377450#LI01736#03186780621111ddb4c432b150008004#SAPEngine_Application_Thread[impl:3]_10##0#0#Error#1#/System/Database/sql/jdbc/common#Java#com.sap.sql_0019##Exception of type com.sap.sql.log.OpenSQLException caught: The SQL statement "INSERT INTO "KMC_SUB_RCPT" ("ID","RECIPIENT","RCPTTYPE","UNSUBSCRIBED") VALUES ('50cdd784-51ac-2810-2393-ea9709f50de3','LI01736','0','X')" contains the semantics error[s]: - 1:27 - the column >>ID<< is undefined in the current scope
[EXCEPTION]
#3#com.sap.sql.log.OpenSQLException#The SQL statement "INSERT INTO "KMC_SUB_RCPT" ("ID","RECIPIENT","RCPTTYPE","UNSUBSCRIBED") VALUES ('50cdd784-51ac-2810-2393-ea9709f50de3','LI01736','0','X')" contains the semantics error[s]: - 1:27 - the column >>ID<< is undefined in the current scope
#com.sap.sql.log.OpenSQLException: The SQL statement "INSERT INTO "KMC_SUB_RCPT" ("ID","RECIPIENT","RCPTTYPE","UNSUBSCRIBED") VALUES ('50cdd784-51ac-2810-2393-ea9709f50de3','LI01736','0','X')" contains the semantics error[s]: - 1:27 - the column >>ID<< is undefined in the current scope
at com.sap.sql.jdbc.common.StatementAnalyzerImpl.check(StatementAnalyzerImpl.java:38)
at com.sap.sql.jdbc.common.StatementAnalyzerImpl.preprepareStatement(StatementAnalyzerImpl.java:101)
at com.sap.sql.jdbc.common.StatementAnalyzerImpl.preprepareStatement(StatementAnalyzerImpl.java:87)
at com.sap.sql.jdbc.common.CommonStatementImpl.executeUpdate(CommonStatementImpl.java:159)
at com.sap.engine.services.dbpool.wrappers.StatementWrapper.executeUpdate(StatementWrapper.java:162)
at com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionsOpenSQL$SqlCommand.executeUpdate(SubscriptionsOpenSQL.java:3834)
at com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionsOpenSQL.unsubscribe(SubscriptionsOpenSQL.java:2127)
at com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionManager.unsubscribe(SubscriptionManager.java:3226)
at com.sapportals.wcm.repository.service.subscription.wcm.SubscriptionManager.unsubscribe(SubscriptionManager.java:3205)
at com.sapportals.wcm.repository.service.subscription.wcm.ActionInboxItemProducer.executeItemAction(ActionInboxItemProducer.java:222)
at com.sapportals.wcm.service.actioninbox.wcm.ActionInboxService.executeItemAction(ActionInboxService.java:610)
at com.sapportals.wcm.service.actioninbox.wcm.ActionInboxService.executeItemActions(ActionInboxService.java:1221)
at com.sapportals.wcm.control.actioninbox.ActionInboxDetailsControl.onClick(ActionInboxDetailsControl.java:396)
Any Idea?
Regards,
GerhardStatement statement = connection.createStatement();
//createing a statement object
String query= "INSERT INTO table......"
output.append("\nSending query:" + connection.nativeSQL(query));
int result = statement.executeUpdate(query);//updates database wit record
if (result==1)
output.append("\ninsertation successfull");
JOptionPane.showMessageDialog(null,"Insertation successfull ",
JOptionPane.INFORMATION_MESSAGE);
else
output.append("\ninsertation unsuccessfull");
JOptionPane.showMessageDialog(null,"Insertation unsuccessfull",
JOptionPane.WARNING_MESSAGE);
statement.close();
have left out the trys and catches and some other bits and pieces that i dont think ud need its the bare bones but it might help or at least give u an idea. have used this code before to do something similar. -
INSERT INTO statement in java servlet.
Hiya
Was wondering if anyone knew how to use variables from an html form into a sql insert into statement? The constants work ok below, its just getting the variables to work.
//constants work ok.
rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ('un', 'test2', 'test2', 'test2', 'test', 'test', 'test', 'test', 'test')");
//doesn't do anything no errors.
rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ( '"+uname+"', " + " '"+fname+"', " + " '"+sname+"'," + "'"+address1+"'," + "'"+address2+"'," + "'"+town+"'," + "'"+county+"'," + "'"+postcode+"')");<html>
<head>
<title>
CreateAccount
</title>
</head>
<body>
<form method=get action=/servlet/website.CreateAccount>
<p> Username:
<input type=text name="username"> </p>
<p> Password:
<input type=text name="password"> </p>
<p> First Name:
<input type=text name="firstname"> </p>
<p> Surname:
<input type=text name="surname"> </p>
<p> 1st Line of Address:
<input type=text name="1address"> </p>
<p> 2nd Line of Address:
<input type=text name="2address"> </p>
<p> Town:
<input type=text name="town"> </p>
<p> County:
<input type=text name="county"> </p>
<p> Postcode:
<input type=text name="postcode"> </p>
<input type=submit>
</form>
</body>
</html>
package website;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CreateAccount extends HttpServlet {
private static final String CONTENT_TYPE = "text/html";
/**Initialize global variables*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
/**Process the HTTP Get request*/
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ResultSet rs = null;
Connection con = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("1address");
String address2 = req.getParameter("2address");
String town = req.getParameter("town");
String county = req.getParameter("county");
String postcode = req.getParameter("postcode");
try {
// Load the database driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Get a Connection to the database
con = DriverManager.getConnection("jdbc:odbc:account", "", "");
//Add the data into the database
try
String sql = "INSERT INTO ACCOUNTS " + " VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, uname);
statement.setString(2, fname);
statement.setString(3, sname);
statement.setString(4, address1);
statement.setString(5, address2);
statement.setString(6, town);
statement.setString(7, county);
statement.setString(8, postcode);
int numRowsChanged = statement.executeUpdate(sql);
statement.close();
//Statement stmt = null;
//stmt = con.createStatement();
//Create a Statement object
//constants work ok.
//rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ('uname', 'test2', 'test2', 'test2', 'test', 'test', 'test', 'test', 'test')");
catch (Exception e)
// show that the new account has been created
out.println("<p> New account created: </p>");
out.println(" '"+uname+"'");
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
finally {
// Always close the database connection.
try {
if (con != null) con.close();
catch (SQLException ignored) { }
}ok now the regular statement with constant values inserts data into the database (the regular statement is being used with a result set ) but the prepared statement does not - there are no error messages but it does not insert any data either. The data is going into the variables due to the system.out.println, but is it going into the prepared statement? I believe the prepared statement is being executed with the executeupdate method. -
Strange result from insert into...select query
Hello guys,
I need your preciuos help for a question maybe simple, but that I can't explain by myself!
I have a query of "insert into...select" that, as I have explained in the title, returns a strange result. In facts, If I execute ONLY the SELECT statement the query returns the expected result (so 2 rows); instead If I execute the entire statement, that is the "insert into...select", the query returns 0 rows inserted!!
Following an example of the query:
INSERT
INTO TITOLI_ORI
COD_TITOLO_RICCONS ,
D_ESTRAZIONE ,
COD_SOCIETA ,
COD_PIANO_CONTABILE ,
COD_CONTO_CONTABILE ,
COD_RUBRICATO_STATISTICO_1 ,
COD_NDG ,
NUM_ESEGUITO ,
CUR_IMPORTO_RICCONS ,
CUR_IMPORTO_BICO ,
FLG_MODIFICATO ,
CUR_NON_ASSEGNATO ,
FLG_QUOTATO ,
COD_CATEG ,
TIP_COPERTURA ,
TIPTAS_TITOLO
SELECT NEWID,
'28-feb-2111',
COD_SOCIETA,
COD_PIANO_CONTABILE,
COD_CONTO_CONTABILE,
COD_RUBRICATO_STATISTICO_1,
COD_NDG,
NUM_ESEGUITO,
CUR_VAL_IMPEGNI,
'ABC' as CUR_IMPORTO_BICO,
0 as FLG_MODIFICATO,
NULL as CUR_NON_ASSEGNATO,
FLG_QUOTATO,
COD_CATEG,
TIP_COPERTURA,
TIP_TASSO
FROM
(SELECT S.COD_SOC AS COD_SOCIETA,
S.TIP_PIANO_CNTB AS COD_PIANO_CONTABILE,
S.COD_CONTO_CNTB AS COD_CONTO_CONTABILE,
S.COD_RUBR_STAT AS COD_RUBRICATO_STATISTICO_1,
TRC.COD_RAGGR_IAS AS COD_RAGGRUPPAMENTO_IAS,
TRC.COD_NDG AS COD_NDG,
TRC.COD_ESEG AS NUM_ESEGUITO,
CAST((TRC.IMP_PLUS_MINUS_VAL/TRC.IMP_CAMB) AS FLOAT) AS CUR_VAL_IMPEGNI,
TRC.TIP_QUOTAZ AS FLG_QUOTATO,
TRC.COD_CAT_TIT AS COD_CATEG,
TIP_COP AS TIP_COPERTURA,
T.TIP_TASSO AS TIP_TASSO
FROM S_SLD_CNTB S
INNER JOIN
(SELECT DISTINCT COD_SOC,
TIP_PIANO_CNTB,
COD_CONTO_CNTB,
COD_RUBR_STAT ,
COD_INTER_TIT AS COD_INTER
FROM S_COLLEG_CONTO_CNTB_TIT
WHERE COD_SOC = 'ME'
) CCC
ON S.COD_SOC = CCC.COD_SOC
AND S.TIP_PIANO_CNTB = CCC.TIP_PIANO_CNTB
AND S.COD_CONTO_CNTB = CCC.COD_CONTO_CNTB
AND S.COD_RUBR_STAT = CCC.COD_RUBR_STAT
INNER JOIN S_TIT_RICCONS TRC
ON CCC.COD_INTER = TRC.COD_INTER_TIT
AND CCC.COD_SOC = TRC.COD_SOC
AND TRC.COD_RAGGR_IAS = RTRIM('VALUE1 ')
AND TRC.COD_RAGGR_IAS NOT IN ('VALUE2')
AND TRC.DES_TIP_SLD_TIT_RICCONS IN ('VALUE3')
AND TRC.DES_MOV_TIT = RTRIM('VALUE4 ')
AND TRC.COD_CAT_TIT = RTRIM('VALUE4 ')
AND TRC.COD_INTER_TIT = RTRIM('VALUE5')
AND '28-feb-2011' = TRC.DAT_RIF
LEFT JOIN S_TIT T
ON T.COD_INTER_TIT = TRC.COD_INTER_TIT
AND T.COD_SOC = TRC.COD_SOC
AND '28-feb-2011' = T.DAT_RIF
INNER JOIN S_ANAG_SOGG AG
ON TRC.COD_NDG = AG.COD_NDG
AND AG.COD_SOC = TRC.COD_SOC
AND '28-feb-2011' = AG.DAT_RIF
WHERE S.DAT_RIF = '28-feb-2011'
AND (S.FLG_ANULL_BICO = 0
OR S.FLG_ANULL_BICO IS NULL)
AND S.COD_SOC = 'V6'
AND LENGTH(RTRIM(S.COD_CONTO_CNTB)) = 10
AND S.TIP_PIANO_CNTB = 'V7'
AND TRC.IMP_PLUS_MINUS_VAL < 0
AND SUBSTR(S.COD_CONTO_CNTB,1,7) IN (RTRIM('VALUE8 '))
Thanks a lotRight, I have executed this steps:
- I have changed the query with the select count(*)
- Changed the insert into with the select count(*)
- Executed the insert into
These are the result:
SQL> select count(*) from TITOLI_ORI2;
COUNT(*)
1
BUT:
SQL> select * from TITOLI_ORI2;
A
0
The insert into that I've modified is this:
INSERT INTO bsc.TITOLI_ORI2
select count(*)
FROM
(SELECT bsc.NEWID,
TO_DATE('28-feb-2111','DD-MON-YYYY') as data,
COD_SOCIETA,
COD_PIANO_CONTABILE,
COD_CONTO_CONTABILE,
COD_RUBRICATO_STATISTICO_1,
COD_NDG,
NUM_ESEGUITO,
CUR_VAL_IMPEGNI,
'ABC' AS CUR_IMPORTO_BICO,
0 AS FLG_MODIFICATO,
NULL CUR_NON_ASSEGNATO,
FLG_QUOTATO,
COD_CATEG,
TIP_COPERTURA,
TIP_TASSO
FROM
(SELECT S.COD_SOC AS COD_SOCIETA,
S.TIP_PIANO_CNTB AS COD_PIANO_CONTABILE,
S.COD_CONTO_CNTB AS COD_CONTO_CONTABILE,
S.COD_RUBR_STAT AS COD_RUBRICATO_STATISTICO_1,
TRC.COD_RAGGR_IAS AS COD_RAGGRUPPAMENTO_IAS,
TRC.COD_NDG AS COD_NDG,
TRC.COD_ESEG AS NUM_ESEGUITO,
CAST((TRC.IMP_PLUS_MINUS_VAL/TRC.IMP_CAMB) AS FLOAT) AS CUR_VAL_IMPEGNI,
TRC.TIP_QUOTAZ AS FLG_QUOTATO,
TRC.COD_CAT_TIT AS COD_CATEG,
TIP_COP AS TIP_COPERTURA,
T.TIP_TASSO AS TIP_TASSO
FROM bsc.S_SLD_CNTB S
INNER JOIN
(SELECT DISTINCT COD_SOC,
TIP_PIANO_CNTB,
COD_CONTO_CNTB,
COD_RUBR_STAT ,
COD_INTER_TIT AS COD_INTER
FROM bsc.S_COLLEG_CONTO_CNTB_TIT
WHERE COD_SOC = 'ME'
) CCC
ON S.COD_SOC = CCC.COD_SOC
AND S.TIP_PIANO_CNTB = CCC.TIP_PIANO_CNTB
AND S.COD_CONTO_CNTB = CCC.COD_CONTO_CNTB
AND S.COD_RUBR_STAT = CCC.COD_RUBR_STAT
INNER JOIN bsc.S_TIT_RICCONS TRC
ON CCC.COD_INTER = TRC.COD_INTER_TIT
AND CCC.COD_SOC = TRC.COD_SOC
AND TRC.COD_RAGGR_IAS = RTRIM('HFT ')
AND TRC.COD_RAGGR_IAS NOT IN ('GPO')
AND TRC.DES_TIP_SLD_TIT_RICCONS IN ('DISPONIBILI')
AND TRC.DES_MOV_TIT = RTRIM('CONSEGNARE ')
AND TRC.COD_CAT_TIT = RTRIM('OBBLIGAZIONE ')
AND TRC.COD_INTER_TIT = RTRIM('334058')
AND '28-feb-2011' = TRC.DAT_RIF
LEFT JOIN bsc.S_TIT T
ON T.COD_INTER_TIT = TRC.COD_INTER_TIT
AND T.COD_SOC = TRC.COD_SOC
AND '28-feb-2011' = T.DAT_RIF
INNER JOIN bsc.S_ANAG_SOGG AG
ON TRC.COD_NDG = AG.COD_NDG
AND AG.COD_SOC = TRC.COD_SOC
AND '28-feb-2011' = AG.DAT_RIF
WHERE S.DAT_RIF = '28-feb-2011'
AND (S.FLG_ANULL_BICO = 0
OR S.FLG_ANULL_BICO IS NULL)
AND S.COD_SOC = 'ME'
AND LENGTH(RTRIM(S.COD_CONTO_CNTB)) = 10
AND S.TIP_PIANO_CNTB = 'IS'
AND TRC.IMP_PLUS_MINUS_VAL < 0
AND SUBSTR(S.COD_CONTO_CNTB,1,7) IN (RTRIM('P044C11 '))
Another time the strange result returns!!
And I've created the table TITOLI_ORI2 as create table TITOLI_ORI2 (a number); to contain the number result of the query. -
T-SQL - PL/SQL conversion: insert into ... select problem
Hi!
If I have an insert into ... select statement in T-SQL without a 'from' clause:
bq. insert into sometable (foo, bar) \\ select 5, case when @bar=5 then 4 else 3 end
its translation is:
bq. INSERT INTO sometable \\ ( foo, bar ) \\ VALUES ( 5, CASE \\ WHEN 5 = 5 THEN 4 \\ ELSE 3 \\ END col );
and I got: ORA-00917: "missing comma" for that. I'm not sure if it's a bug in the migration code, or is there a trick so that I can use 'CASE' in an insert into .. values statement somehow?
ZoliYou have to remove the column name. I just simplified your test case to check and it's working:
CREATE TABLE test(
id NUMBER
INSERT
INTO test(id)
VALUES(CASE WHEN 5=5 THEN 4 ELSE 3 END)
SELECT *
FROM test
;C. -
Apex Application inserting into two tables from two regions in a page
Hey Guys,
Fairly new to apex like two days. So please bare with me. I am using apex 4.0.2.00.07.
I have a page with two regions. The first region has only one row and I have no problems accessing it and inserting those values into the table this is what I used to access one column from that one row APEX_APPLICATION.G_F03(1)
The second region is an interactive report, to which I have managed to add a checkbox and a textbox.
1)So if a checkbox has been checked off the row should be inserted
2) if the textbox has been entered it should replaceone of the values.
My question is how to access the second region? I started a loop based on the rows in the collection but that is as far as I got.
FOR idx IN 1..l_collectionTable_name
loop
end loop
Any help would be greatly appreciated?
Thank you
Edited by: Aj05 on Aug 2, 2012 2:10 PMHi Phil I used the following code
<cfquery name="qArrivalDates" datasource="rayannesql">
SET NOCOUNT ON
INSERT INTO booking (book_made, book_checkin_date,
book_checkout_date, book_adults, book_children)
VALUES('#FORM.book_made#','#FORM.book_checkin_date#','#FORM.book_checkout_date#','#FORM.bo ok_adults#','#FORM.book_children#')
SELECT SCOPE_IDENTITY() AS theNewId;
SET NOCOUNT OFF
</cfquery>
<cfquery name="qArrivalDates" datasource="rayannesql">
INSERT INTO Customer( firstname, lastname, address, address2,
city, state, postalcode, country, phone, mobile, email, notes)
Values (#qArrivalDates.theNewId# '#FORM.firstname#',
'#FORM.lastname#', '#FORM.address#', '#FORM.address2#',
'#FORM.city#', '#FORM.state#', '#FORM.postalcode#',
'#FORM.country#', '#FORM.phone#', '#FORM.mobile#', '#FORM.email#',
'#FORM.notes#' )
</cfquery>
When I tried to complete the form, I got the following error
Macromedia][SequeLink JDBC Driver][ODBC
Socket][Microsoft][SQL Native Client][SQL Server]Incorrect syntax
near 'Fred'.
The error occurred in
C:\Inetpub\wwwroot\rayanne\customerinsertsql.cfm: line 16
14 : <cfquery name="qArrivalDates"
datasource="rayannesql">
15 : INSERT INTO Customer( firstname, lastname, address,
address2, city, state, postalcode, country, phone, mobile, email,
notes)
16 : Values (#qArrivalDates.theNewId# '#FORM.firstname#',
'#FORM.lastname#', '#FORM.address#', '#FORM.address2#',
'#FORM.city#', '#FORM.state#', '#FORM.postalcode#',
'#FORM.country#', '#FORM.phone#', '#FORM.mobile#', '#FORM.email#',
'#FORM.notes#' )
17 : </cfquery> -
Insert into using a select and dynamic sql
Hi,
I've got hopefully easy question. I have a procedure that updates 3 tables with 3 different update statements. The procedure goes through and updates through ranges I pass in. I am hoping to create another table which will pass in those updates as an insert statement and append the data on to the existing data.
I am thinking of using dynamic sql, but I am sure there is an easy way to do it using PL/SQL as well. I have pasted the procedure below, and what I'm thinking would be a good way to do it. Below I have pasted my procedure and the bottom is the insert statement I want to use. I am faily sure I can do it using dynamic SQL, but I am not familiar with the syntax.
CREATE OR REPLACE PROCEDURE ACTIVATE_PHONE_CARDS (min_login in VARCHAR2, max_login in VARCHAR2, vperc in VARCHAR2) IS
BEGIN
UPDATE service_t SET status = 10100
WHERE poid_id0 in
(SELECT poid_id0 FROM service_t
WHERE poid_type='/service/telephony'
AND login >= min_login AND login <= max_login);
DBMS_OUTPUT.put_line( 'Service Status:' || sql%rowcount);
UPDATE account_t SET status = 10100
WHERE poid_id0 IN
(SELECT account_obj_id0 FROM service_t
WHERE poid_type = '/service/telephony'
AND login >= min_login AND login <= max_login);
DBMS_OUTPUT.put_line( 'Account Status:' || sql%rowcount);
UPDATE account_nameinfo_t SET title=Initcap(vperc)
WHERE obj_id0 IN
(SELECT account_obj_id0 FROM service_t
WHERE poid_type='/service/telephony'
AND login >=min_login AND login <= max_login);
DBMS_OUTPUT.put_line('Job Title:' || sql%rowcount);
INSERT INTO phone_card_activation values which = 'select a.status, s.status, s.login, to_char(d.sysdate,DD-MON-YYYY), ani.title
from account_t a, service_t s, account_nameinfo_t ani, dual d
where service_t.login between service_t.min_login and service_t.max_login
and ani.for_key=a.pri_key
and s.for_key=a.pri_key;'
END;
Thanks for any advice, and have a good weekend.
GeordieCorrect my if I am wrong but aren't these equal?
UPDATE service_t SET status = 10100
WHERE poid_id0 in
(SELECT poid_id0 FROM service_t
WHERE poid_type='/service/telephony'
AND login >= min_login AND login <= max_login);
(update all the records where there id is in the sub-query that meet the WHERE Clause)
AND
UPDATE service_t SET status = 10100
WHERE poid_type='/service/telephony'
AND login >= min_login AND login <= max_login);
(update all the records that meet the WHERE Clause)
This should equate to the same record set, in which case the second update would be quicker without the sub-query. -
Diffrence between backend insert and front end insert into a table.
I am developing a conversion program for tax exemption. For this program only ZX_EXEMPTIONS table is used to populate the data and we got confirmation from Oracle also regarding this.For inserting the data into this table we are taking the max of tax_exemption_id which is pk for this table and adding one to it and inserting into the table. But problem here is after inserting from back end we are not able to insert from front end.
It seems backend data is holding the tax_exemption_id which is suppose to reserve by front end data.Please explain the different behavior of populating of tax_exemption_id from front end and back end.Hi,
i think the problem is that you are using max-value + 1 for tax_exemption_id. But as ZX_EXEMPTIONS is using sequence ZX_EXEMPTIONS_S
for primary key generation, you encounter situation that you are increasing PK Id for this table without increasing sequence value.
When trying to insert rows from front end - which probably uses sequence value - it tries to use a sequence value already used by your backend
process (which generated it by Maxvalue + 1) and would then encounter a primary key violation.
I think you should use sequence mentioned above to generate your PK Ids in backend process as well. And before doing so, check current value
of ZX_EXEMPTIONS_S, as you might need to rebuild the sequence in order to select nextval sucessfully for both frontend and backend.
Regards
Maybe you are looking for
-
Environment variables (user) created at OS level dont show up in BIDS 2008
Environment variables (user) created at OS level don't show up in BIDS 2008. I had a variable ConfigLocation created and it is not showing up when I am trying to configure it in BIDS Is this a known issue or a bug? Now in BIDS it doesnt show up Mudas
-
How do I restrict access to 4 devices using ACS
Currenlty in our ACS we have Group A configured to have access to all network devices-f with ull privilege level 15 access to all devies We are now trying to implement 4 new users, however we only want them to have access to 4 devices-routers (4 IP a
-
I've been on the phone to Apple about this but never enough time. My mail will send but not receive and all the internet setting are correct. I was told to use the reinstall CD as I must have bad mail program (?) However when I searched for my disks
-
Html code for closing the browser window on logoff.
Hello, I am using the logoff redirecrt url feauture to divert the logoff page to a custom made html page. I want this page should be closed automatically after being called i.e. when I click the logoff button it should divert to this custom html page
-
Importing excel with missing fonts
I've got a spreadsheet for my employees and the spreadsheet does the neccessary calculations and I then import it into indesign cs2 on mac. The problem is it claims the fonts are missing fonts and the layout is compromised. I then have to painstaking