Database post example
hi, some time ago i asked in this forum about examples about flash/sql, i got this as a reference (tnx ned murphy):
http://www.gotoandlearn.com/play?id=20
this seems to work and the example is clear and great for part of the job, though it only shows how to read from the database. as i said, that is only part of the job since it only shows how to read from the database, i also need to send to the database a string of about 7k (more or less 5000 to 700 bytes, in a single string) i would like to do that trough php, since it should use the same php session id. does anyone have references to this? (write to a databse from flash, if possible using php as middle layer)
tnx
Google is one of the best resources available for finding things such as you are looking for. Use search terms such as "AS3 PHP SQL" and maybe throw on "tutorial" as well, and you should come up with a few useful links you can build from.
Similar Messages
-
SAPINST failed step "Install Oracle Database (post processing)"
i will install ep6.0 with oracle database 9.2.0.4 on sun solaris.
the SAPINST failed at the step "Install Oracle Database (post processing) with follow error.
the oui - installer (runinstaller) finished sucessfully.
ERROR 2004-08-31 16:05:17
CJS-00084 SQL statement or script failed. DIAGNOSIS: Error message: ORA-01501: CREATE DATABASE failedORA-01101: database being created currently mounted by some other instance
Disconnected from Oracle9i Enterprise Edition Release 9.2.0.4.0 - 64bit Production
With the Partitioning optionJServer Release 9.2.0.4.0 - Production. SOLUTION: See ora_sql_results.log and the Oracle documentation for details.
no user is logged on the Database. Database is not running (is shutdowned and unmounted). No Oracle process is running.
pleas help.
thanks
armin hadersbeckHi Armin,
We're going to install EP 6 stack3 with Oracle 9.2.0.4 and Solaris 9. We have exactly the same error as you during sapinst.
How do you solved that ?
Thanks a lot for your help,
Regards from Mexico,
Diego -
Passing Array of java objects to and from oracle database-Complete Example
Hi all ,
I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
First thinsg first
i) Create a Java Value Object which you want to pass .
create or replace and compile java source named Person as
import java.sql.*;
import java.io.*;
public class Person implements SQLData
private String sql_type = "PERSON_T";
public int person_id;
public String person_name;
public Person () {}
public String getSQLTypeName() throws SQLException { return sql_type; }
public void readSQL(SQLInput stream, String typeName) throws SQLException
sql_type = typeName;
person_id = stream.readInt();
person_name = stream.readString();
public void writeSQL(SQLOutput stream) throws SQLException
stream.writeInt (person_id);
stream.writeString (person_name);
ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
you should see a message called "Java created."
iii) Now create your object Types
CREATE TYPE person_t AS OBJECT
EXTERNAL NAME 'Person' LANGUAGE JAVA
USING SQLData (
person_id NUMBER(9) EXTERNAL NAME 'person_id',
person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
iv) Now create a table of Objects
CREATE TYPE person_tab IS TABLE OF person_t;
v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
create or replace
procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
as
l_person_id Number;
l_person_name Varchar2(200);
l_person person_t;
l_p_arrayout person_tab;
errm Varchar2(2000);
begin
l_p_arrayout := person_tab();
for i in 1 .. p_array.count
loop
l_p_arrayout.extend;
insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
l_person_id := p_array(i).person_id;
l_person_name := p_array(i).person_name;
l_person := person_t(null,null);
l_person.person_id := l_person_id + 5;
l_person.person_name := 'Out Record ' ||l_person_name ;
l_p_arrayout(i) := l_person;
end loop;
p_arrayout := l_p_arrayout;
l_person_id := p_arrayout.count;
for i in 1 .. p_arrayout.count
loop
insert into person_test values(l_person_id, p_arrayout(i).person_name);
end loop;
commit;
EXCEPTION WHEN OTHERS THEN
errm := SQLERRM;
insert into person_test values(-1, errm);
commit;
end;
vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
import java.util.Date;
import java.io.*;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ArrayDemo
public static void passArray() throws SQLException
Connection conn = getConnection();
ArrayDemo a = new ArrayDemo();
Person pn1 = new Person();
pn1.person_id = 1;
pn1.person_name = "SunilKumar";
Person pn2 = new Person();
pn2.person_id = 2;
pn2.person_name = "Superb";
Person pn3 = new Person();
pn3.person_id = 31;
pn3.person_name = "Outstanding";
Person[] P_arr = {pn1, pn2, pn3};
Person[] P_arr_out = new Person[3];
ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
ARRAY array_to_pass =
new ARRAY( descriptor, conn, P_arr);
OracleCallableStatement ps =
(OracleCallableStatement )conn.prepareCall
( "begin give_me_an_array(?,?); end;" );
ps.setARRAY( 1, array_to_pass );
ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
ps.execute();
oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
Object[] personDetails = (Object[]) returnArray.getArray();
Person person_record = new Person();
for (int i = 0; i < personDetails.length; i++) {
person_record = (Person)personDetails;
System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
public static void main (String args[]){
try
ArrayDemo tfc = new ArrayDemo();
tfc.passArray();
catch(Exception e) {
e.printStackTrace();
public static Connection getConnection() {
try
Class.forName ("oracle.jdbc.OracleDriver");
return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
"username", "password");
catch(Exception SQLe) {
System.out.println("IN EXCEPTION BLOCK ");
return null;
and thats it. you are done.
Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
Thanks
Sunil.sHi Sunil,
I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
at oracle.sql.ARRAY.<init>(ARRAY.java:152)
at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
Here's a code snippet I used :
Object optionVal[] = {optionArr[0]}; // optionArr[0] is an Option object which has three properties
oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
I'll appreciate if you can provide some information.
Regards,
Shamik -
Error on Oracle 11gR2 RAC database Post upgrade step
[Upgrade the Oracle Clusterware Configuration|http://docs.oracle.com/cd/E11882_01/server.112/e23633/afterup.htm] Problem Description:
O.S Version: HP-UX B.11.31 U ia64
It is upgrading of Oracle RAC 2 node database from 11.1.0.7.0 to 11.2.0.3.0
I receive following error while perfoming the post upgrade step
indba1 racdb> srvctl upgrade database -d racdb -o /app/oracle/product/11.2.0.3/db
PRCD-1231 : Failed to upgrade configuration of database racdb to version 11.2.0.3.0 in new Oracle home /app/oracle/product/11.2.0.3/db
PRKC-1136 : Unable to find version for database with name racdb
Actually I am performing the step "Upgrade the Oracle Clusterware Configuration" whill getting the error.
When I tried on below;
indba1 racdbp> srvctl upgrade database -d racdb -o /app/oracle/product/11.2.0.3/db
PRCD-1231 : Failed to upgrade configuration of database racdb to version 11.2.0.3.0 in new Oracle home /app/oracle/product/11.2.0.3/db
PRKC-1136 : Unable to find version for database with name racdbOutput from Oracle 11.1.0.7 Home:
oracle@indba1:/app/oracle/product/11g/db_1 $ srvctl config database -d racdb
PRKR-1001 : cluster database racdb does not exist
PRKO-2005 : Application error: Failure in getting Cluster Database Configuration for: racdb
Output from Oracle 11.2.0.3 Home:
oracle@usfsdba1:/app/oracle/product/11.2.0.3/db $ srvctl config database -d racdb
PRKR-1001 : cluster database racdb does not exist
PRKO-2005 : Application error: Failure in getting Cluster Database Configuration for: racdb -
Oracle Database 11g Examples CD
Hi
Please can anybody let me know where i can download the 11g examples CD for linuxx86 as early as possinle
Does it come s with the 11g release 2 patchset?
Please let me know
Thanks
Vinay Varma SHi,
It should be here or else it is not available:
http://www.oracle.com/technetwork/database/enterprise-edition/downloads/112020-zlinux64-352074.html
Best regards,
Rafi.
http://rafioracledba.blogspot.com/ -
Groupwise database post office errors
Thanks in advance for any answers you can give me.
We had some corruption in our groupwise databases today, We have two users who's gwcheck comes back as
Problem 39- Unknown file useremc.dba - 64652288 bytes,
They cannot login to their mailbox and when you email them you the message
Tried to change a locked setting
Error = D013
What would be the best recourse in fixing this?
We also have a few people whos password is now gone. everything is there but you cant login, if you try to change it in console one it changes, but it does not update the password in groupwise,
any help would be appreciated.
groupwise 8.02 hotfix 1Originally Posted by bmcgehee
Thanks in advance for any answers you can give me.
We had some corruption in our groupwise databases today, We have two users who's gwcheck comes back as
Problem 39- Unknown file useremc.dba - 64652288 bytes,
They cannot login to their mailbox and when you email them you the message
Tried to change a locked setting
Error = D013
What would be the best recourse in fixing this?
We also have a few people whos password is now gone. everything is there but you cant login, if you try to change it in console one it changes, but it does not update the password in groupwise,
any help would be appreciated.
groupwise 8.02 hotfix 1
What kind of corruption did you have? And what happened that led to this?
It would be good to know what OS, version and SP level you are running on and what filesystem the GroupWise dibs are on?
As for the unknown file error... could be normal as the file mentioned is a backup file or the database, typically created by GroupWise during certain gwcheck maintenance tasks.
Is there a .db file for the user in question (e.g. useremc.db in the offusr folder?).
In all cases tread carefully as you first need to determine what might be broken before trying to fix anything.
-Willem -
Non-trivial Database editing examples
Hi everyone,
I'm searching for examples of database editing and setting properties that are more complex than the ones that ship with LabWindows/CVI. As far as I can tell, these don't even edit the database, they just manipulate aliases and parse through the different clusters/frames/signals, despite being titled "Managing Databases". Anyone out there know where I can find this kind of info? Thanks!
- Brandon
EDIT: I'm using the XNET APIThose examples do edit a database, the database just happens to be in memory instead of on disk. To be honest whenever I need to actually edit a DBC file I usually resort to Vectors database editing software which runs without needing any particular hardware or software license.
But if you are strickly in the XNET world, import the DBC, then use the "Database Editor" to edit the XNET database. This is saved as an XML but contains much of the same information as DBC. You can also programatically import a DBC to use in XNET if you periodically get updates.
My conversion library does this in the examples.
https://decibel.ni.com/content/docs/DOC-39793
Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously. -
Question about JAI posted example?
Thank you
I just wondered if I could ask, I found this example JAI code on the web. The code compiles, but in the example said they missed out some lines at the begining, do you these missing lines were to read-in a image?
import java.awt.*;
import java.awt.image.*;
import javax.media.jai.*;
public class CreateRGBImage{
public static void main(String[] args){
int width = 121; int height = 121; // Dimensions of the image
byte[] data = new byte[width*height*3]; // Image data array.
int count = 0; // Temporary counter.
for(int w=0;w<width;w++) // Fill the array with a pattern.
for(int h=0;h<height;h++){
data[count+0] = (count % 2 == 0) ? (byte)255: (byte) 0;
data[count+1] = 0;
data[count+2] = (count % 2 == 0) ? (byte) 0: (byte)255;
count += 3;
// Create a Data Buffer from the values on the single image array.
DataBufferByte dbuffer = new DataBufferByte(data,width*height*3);
// Create an pixel interleaved data sample model.
SampleModel sampleModel = RasterFactory.
createPixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
width,height,3);
// Create a compatible ColorModel.
ColorModel colorModel = PlanarImage.createColorModel(sampleModel);
// Create a WritableRaster.
Raster raster = RasterFactory.createWritableRaster(sampleModel,dbuffer,
new Point(0,0));
// Create a TiledImage using the SampleModel.
TiledImage tiledImage = new TiledImage(0,0,width,height,0,0,
sampleModel,colorModel);
// Set the data of the tiled image to be the raster.
tiledImage.setData(raster);
// Save the image on a file.
JAI.create("filestore",tiledImage,"rgbpattern.tif","TIFF");
}I didnot go thru the code you posted but I know that the following workstry {
// From file
AudioInputStream stream = AudioSystem.getAudioInputStream(new File("audiofile"));
// From URL
stream = AudioSystem.getAudioInputStream(new URL("http://hostname/audiofile"));
// At present, ALAW and ULAW encodings must be converted
// to PCM_SIGNED before it can be played
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits()*2,
format.getChannels(),
format.getFrameSize()*2,
format.getFrameRate(),
true); // big endian
stream = AudioSystem.getAudioInputStream(format, stream);
// Create the clip
DataLine.Info info = new DataLine.Info(
Clip.class, stream.getFormat(), ((int)stream.getFrameLength()*format.getFrameSize()));
Clip clip = (Clip) AudioSystem.getLine(info);
// This method does not return until the audio file is completely loaded
clip.open(stream);
// Start playing
clip.start();
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (LineUnavailableException e) {
} catch (UnsupportedAudioFileException e) {
} -
Modifying an Access database posted in a SharePoint doclib
I inherited the maintenance of a database used to store data for reporting. I needed to add a simple new query and "union" it to a group of existing queries.
When opening the database, I am prompted to open it read only, or download a copy to my PC to edit (and when finished, upload).
When I download, the queries I need to add to "disappear" - they are no longer listed in the left hand list of objects.
Thinking here is that those queries are soemehow associated with daya that exists only in SharePoint, and not being available on my desktop, no longer appear.
How can I:
a. Determine what those queries are connected to, and
b. Get the queries to appear in the downloaded version so I can peform the necessary edits?
Thnaks in advance.This doesn't work. When you use the Save As... dialog box and open a SharePoint location using HTTP (WebDAV) connection, the dialog box hangs.
Why does every other piece of software use the Windows 7 dialog box but Adobe Reader XI and any software using the Adobe Acrobat 11.0.0.379 Plug-In (e.g. Firefox or IE) not work? -
Could anyone post examples about sendingand receiving messages with SOAP
I am newbie, and want to learn SOAP. Anyone can tell me
where to find many examples about communication between client and server
based on SOAP. The example is in java code should be best.
Many thanks in advanceJava tutorial at http://java.sun.com/webservices/docs/ea1/tutorial/doc/JAXM.ws.html#63873
should be a good starting point.
I have sample code, which creates SOAP header and SOAP elements. THis code gives an idea to create SOAP messages and to parse the SOAP response. Hope this helps.
I pass Application ID and password in SOAP header, used by the Webservices provider to verify my application. In the SOAP elments, I pass a string (called ticket) and ip address. Web services provider will verify the string and return the response along with some attributes related to the user (extended attributes).
import javax.xml.soap.*;
import javax.xml.messaging.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import java.net.*;
import com.sun.net.ssl.internal.ssl.*;
public class AuthenticateTicket extends HttpServlet{
private static ServletConfig Config;
//always use this Name space
private static final String AUTH_WS_NS = "http://some.url.com/ws/";
// parameters to get the properties for AUTH
private static final String AUTH_LOGIN_URL = "http://some.url.com/loginpage/" + "?izAppId=AUTHappl";
private static final String AUTH_WS_URL ="http://some.url.com/loginpage/v4.asmx";
private static final String AUTH_CLIENT_APPL_ID = "AUTHappl";
private static final String AUTH_CLIENT_APPL_PSWD = "AUTHappl";
* init
* @param ServletConfig
* @return void
public void init(ServletConfig config) throws ServletException {
Config = config;
* service
* This is where the servlet get invoked.
* @param HttpServletRequest
* @param HttpServletResponse
* @return void
* @throws ServletException
* @throws IOException
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("------- service() AuthenticateTicket -------");
String host = request.getRemoteAddr();
String izTicket = request.getParameter("izTicket");
String izStatus = request.getParameter("izStatus");
if (host == null || host.equals("localhost") || izStatus == null || izStatus.trim().equals("") ) {
response.sendRedirect(AUTH_LOGIN_URL);
else if (izTicket != null){
verifyAUTHTicket(host, izTicket);
RequestDispatcher rd = request.getRequestDispatcher("/jspPage1");
rd.forward(request, response);
return;
else {
System.out.println (" NOOOOOOOOO TICKET ");
RequestDispatcher rd = request.getRequestDispatcher("/jspPage1");
rd.forward(request, response);
* <code>createSOAPMessage</code>
* Create the standard AUTH Soap Message.
* This is used during the verifySession process. It creates the message with
* the returnAllAttriutes = true;
* @param String host
* @param String ticketStr
* @return SOAPMessage
* @throws Exception
private static SOAPMessage createSOAPMessage(String host, String ticketStr) throws Exception{
MessageFactory msgFactory = MessageFactory.newInstance( );
SOAPMessage soapMessage = msgFactory.createMessage();
soapMessage.saveChanges();
// Obtain references to the various parts of the message.
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
SOAPBody soapBody = soapEnvelope.getBody();
SOAPHeader header = soapEnvelope.getHeader();
//********** HEADER PART **********
Name headerName = soapEnvelope.createName("wsConsumerCredential", "", AUTH_WS_NS);
SOAPHeaderElement hdrElem = header.addHeaderElement(headerName);
Name authId = soapEnvelope.createName("id");
Name authPwd = soapEnvelope.createName("password");
SOAPElement idElem = hdrElem.addChildElement(authId);
idElem.addTextNode(AUTH_CLIENT_APPL_ID);
SOAPElement pwdElem = hdrElem.addChildElement(authPwd);
pwdElem.addTextNode(AUTH_CLIENT_APPL_PSWD);
//********** BODY PART **********
// Create the <VerifySession> body elements.
Name verifySess = soapEnvelope.createName("VerifySession", "",AUTH_WS_NS);
SOAPBodyElement verifySessBOS = soapBody.addBodyElement(verifySess);
// Create the child elements under the <VerifySession> elements.
Name ticket = soapEnvelope.createName("ticket");
Name userIP = soapEnvelope.createName("userIpAddr");
Name extendedAttr = soapEnvelope.createName("returnExtendedAttributes");
SOAPElement ticketBOS = verifySessBOS.addChildElement(ticket);
SOAPElement ipBOS = verifySessBOS.addChildElement(userIP);
SOAPElement exAttrBOS = verifySessBOS.addChildElement(extendedAttr);
//ticket string
ticketBOS.addTextNode(ticketStr);
ipBOS.addTextNode(host);
//boolean, do we want extended attr?
exAttrBOS.addTextNode("true");
soapMessage.saveChanges();
soapMessage.writeTo(System.out);
return soapMessage;
* <code>parseSOAPResponse</code>
* Parse the standard AUTH Soap Response
* This is used to parse through the AUTH response to gather all the necessary user
* information.
* the returnAllAttriutes = true;
* @param SOAPMessage
* @return User
* @throws Exception
private static void parseSOAPResponse(SOAPMessage response) throws Exception{
String uid, firstName, lastName, email, bolID;
System.out.println (" ============ RESPONSE IS: ====================");
response.writeTo(System.out);
SOAPPart sp = response.getSOAPPart();
SOAPEnvelope soapEnvelope = sp.getEnvelope();
SOAPBody sb = soapEnvelope.getBody();
Name cName = soapEnvelope.createName("VerifySessionResponse","", AUTH_WS_NS);
Iterator it = sb.getChildElements(cName);
SOAPBodyElement verifyResponse = (SOAPBodyElement)it.next();
//System.out.println(" got verifyResponse");
it = verifyResponse.getChildElements(); //iwsResponse
SOAPElement iwsResponse = (SOAPElement)it.next();
//System.out.println(" got iwsResponse");
cName = soapEnvelope.createName("action");
String actionStr = iwsResponse.getAttributeValue(cName);
cName = soapEnvelope.createName("hasErrors");
String hasErrorsStr = iwsResponse.getAttributeValue(cName);
if (actionStr != null && actionStr.equals("Verify") && hasErrorsStr != null
&& hasErrorsStr.equals("false")) {
SOAPElement info = null;
cName = soapEnvelope.createName("sessionInfo","", AUTH_WS_NS);
info = (SOAPElement)iwsResponse.getChildElements(cName).next();
System.out.println (" name is: "+ info.getElementName().getLocalName() + "----" + info.toString());
cName = soapEnvelope.createName("status");
String status = info.getAttributeValue(cName);
System.out.println (" status : " + status) ;
if (status == null || status.indexOf("Active") < 0)
throw new Exception("Session not Active");
SOAPElement userData = null;
cName = soapEnvelope.createName("userAttributes","", AUTH_WS_NS);
userData = (SOAPElement)info.getChildElements(cName).next();
System.out.println (" ===> got user Data ");
cName = soapEnvelope.createName("attribute","", AUTH_WS_NS);
it = userData.getChildElements(cName);
SOAPElement attr = null;
cName = soapEnvelope.createName("accounts","", AUTH_WS_NS);
userData = (SOAPElement)info.getChildElements(cName).next();
System.out.println (" ===> got user Account Data ");
cName = soapEnvelope.createName("account","", AUTH_WS_NS);
it = userData.getChildElements(cName);
SOAPElement account = null;
String loginIDStr=null, typeStr=null, statusStr=null;
while (it.hasNext()){
account = (SOAPElement) it.next();
cName = soapEnvelope.createName("loginId");
loginIDStr = account.getAttributeValue(cName);
cName = soapEnvelope.createName("type");
typeStr = account.getAttributeValue(cName);
cName = soapEnvelope.createName("status");
statusStr = account.getAttributeValue(cName);
if (statusStr.equals("Authenticated")) {
System.out.println("\n\nAuthentication successful");
else {
System.out.println("\n\nAuthentication failed");
* <code>verifyAUTHTicket</code>
* this is for verifySession call to AUTH; It controls the flow with AUTH.
* @param String host
* @param String ticketStr
* @return User
* @throws Exception
public static void verifyAUTHTicket(String host, String izticket) {
SOAPConnection conn =null;
try {
//Creat a message
Provider provider = new Provider();
java.security.Security.addProvider(provider);
SOAPMessage message = createSOAPMessage(host, izticket);
// Get a SOAP connection from the connection factory.
SOAPConnectionFactory connFactory = SOAPConnectionFactory.newInstance( );
// set the default security protocol (shipped with JSSE1.0.2)
System.setProperty ("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
// add the default security provider (again, in JSSE1.0.2)
// java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider() );
conn = connFactory.createConnection( );
// Define the message destination.
URLEndpoint destination = new URLEndpoint(AUTH_WS_URL);
// Send the message and wait for the response.
SOAPMessage response = conn.call( message, destination );
parseSOAPResponse(response);
} catch (Exception ex) {
ex.printStackTrace();
// Close the connection.
finally{
try{
if (conn != null){
conn.close();
catch (SOAPException se){
} -
Need good example HTTP POST Business Service
Hi guys,
I've looked into the provided Reference Implementations in JDE for HTTP Post examples, but they only provided a business service (JRH90I13) and published business service (JPRH90I0) without any C BSFN to execute them. Does anyone have possible examples of how this works?
Thanks in advance.Hi Gregory,
In fact when i used route node to invoke a business service i modified "URL dynamically by setting the value in the pipeline variable $outbound", it worked here.
Same i tried on Service Callout, it did not work. Also when we create a service callout action it expects us to select either "confugure soap body" or "configure payload document" followed by
1) Request Document variable
2) Response Document variable.
What parameter should i set for above fields?
Thanks,
Anup -
Reporting Services 2012 in SharePoint 2010 - SQL database edition?
We currently have a SharePoint 2010 farm, running on a SQL Server 2008 R2 Standard database. On one of the SharePoint 2010 servers, we have an instance of Reporting Services 2008 Enterprise running in SharePoint integrated mode. (We require Enterprise
for data-driven subscriptions)
We'd like to upgrade to Reporting Services 2012 for Data Alerts and a few other new features. However, I noticed something on
this blog stating that the SharePoint 2010 database server edition needs to match the Reporting Services edition. My concern is that I've not seen any official mention of this in Microsoft's documentation, and would like to avoid upgrading to Enterprise
for the SharePoint 2010 database if I can avoid it.
So, what I'd like to run is:
SharePoint 2010
SharePoint database: SQL Server 2008 R2 Standard
Reporting Services 2012 Enterprise
Reporting Services database: same as SharePoint database, so SQL Server 2008 R2 Standard
Is this possible? Or do I need to upgrade the SharePoint database to SQL Server 2008 R2 Enterprise?
Alternatively, could I install a separate database engine just for Reporting Services to host its databases (for example, SQL Server 2012 Enterprise), so I don't have to mess around with upgrading the SP database?While you don't need to upgrade your SQL 2008 R2 to 2012, you will need to install an instance of SQL 2012 & SSRS 2012. They can be side-by-side and independent of each other. The following blog post provides steps to do so,
http://www.madronasg.com/blog/how-configure-sql-server-reporting-services-2012-use-sharepoint-2010#.UuEVd2Ao74Y
Dimitri Ayrapetov (MCSE: SharePoint) -
Create a database link to access SqlServer 2005 view from oracle 11gr2
Hi All,
Greetings for the day.
Though I have seen quite a few posts but just wanted to cross-verfiy and double check hence posting.
Oracle Database : 11gr2
OS :SOLARIS SPARC 64 Bit
SQL Server Database : Sql Server 2005
OS : Windows 2003 32 Bit
The requirement is to access a view residing in the SQL Server 2005 Database using the Oracle Database. This involves creation of a Database link in the Oracle Database to access the SQL Server.
Can you suggest which approach should i follow ( I am able to understand that both do the same job ):
How to Configure DG4MSQL (Oracle Database Gateway for MS SQL Server) 64bit Unix OS (Linux, Solaris, AIX,HP-UX) post install [ID 562509.1]or
How to Configure DG4ODBC on 64bit Unix OS (Linux, Solaris, AIX, HP-UX Itanium) to Connect to Non-Oracle Databases Post Install [ID 561033.1]Will they do the same job ? And can they be used on any OS and version of the SQL Server Database as version information for SQL Server is not specified anywhere?
Please let me know so that I can it forward with Business for approvals and budgetting.
Regards
KKYour question is similar to the post: Oracle 11gr2 connection to Sql Server using dg4msql problem
Please visit: http://stackoverflow.com/questions/4658942/oracle-11gr2-connection-to-sql-server-using-dg4msql-problem
Answer on the website:
You seem to be using the Gateway for MySQL set-up rather than the Heterogeneous Gateway (for ODBC connections). Here is an overview of the process
On SQL Server create a database user and give it read access to the database/tables you want to read via the Oracle database link.
In the gateway home each SQL Server database you want to access should have an init.ora located in $OH/dg4msql/admin in the form initsid.ora where sid is the name of the database to be used in the link (e.g. initbob.ora), so create one
HS_FDS_CONNECT_INFO=msserver1:1234//Example_Database
HS_FDS_TRACE_LEVEL=OFF
HS_FDS_RECOVERY_ACCOUNT=RECOVER
HS_FDS_RECOVERY_PWD=RECOVER
HS_TRANSACTION_MODEL=READ_ONLY
You must now add the new sid to the listener.ora in the gateway home using an additional SID_DESC section inside the existing SID_LIST, for example
(SID_DESC =
(SID_NAME=bob)
(ORACLE_HOME=/oracle/gateway/product/11.2.0)
(ENVS=LD_LIBRARY_PATH=/oracle/gateway/product/11.2.0/dg4msql/driver/lib;/oracle/gateway/product/11.2.0/lib)
(PROGRAM=dg4msql)
You should now stop and restart the gateway listener so that the new sid becomes active. NB a reload is not enough.
You must now add the new sid in the tnsnames.ora file for the listener of each database in which you will create a link. You don't need to do this in the gateway home unless it is also a database home in which you will create a database link.
bob =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = severname.example.com)(PORT = 1690))
(CONNECT_DATA = (SID = bob))
(HS = OK)
NB: The host and port are for the gateway not for the SQL Server database
In each database that requires a link to the MS-SQL database you should create a database link to your new gateway sid.
CREATE PUBLIC DATABASE LINK bob
CONNECT TO "ms_user" IDENTIFIED BY "ms-passwd" USING 'bob';
where ms-user and ms-password are the SQL Server user you created right at the start.
Now you can test the new database link
SELECT COUNT(*) FROM "Table_Name"@bob;
Once you have this working you can alter the initsid.ora file to add parameters to suit your connection. If you do it this way you can easily add and manage many different databases via the gateway.
Hip
Edited by: 1000595 on 04:58 17-04-2013 -
Please compare
methods in C # to connect to SQL Server
database (for example,
3-tier architecture of traditional and
entity Framework(linq to entity or linq to sql object model)
and Linq to SQL) in terms of speed, quality and functionality
to give me tips.
Thank you.
Mojtaba Malakouti.That means we need to compare and post the results here?
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Database Access in Java (Count field incorrect)
Was given a stock tracking application to be edited for use as a Student/Admin login application which accesses a database and adds/deletes/edits student information. When I try to login, I get the following error: [Microsoft][OBDC Microsoft Access Driver]Count Field Incorrect
The driver was set up in the Admin tools in Windows XP.
The columns exist in the database.
//makeDB.java
import java.sql.*;
import java.io.*;
public class MakeDB
public static void main(String[] args) throws Exception
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:saad";
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
// The following code deletes each index and table, if they exist.
// If they do not exist, a message is displayed and execution continues.
System.out.println("Dropping indexes & tables ...");
try
stmt.executeUpdate("DROP INDEX PK_StudentUserBridge ON StudentUserBridge");
catch (Exception e)
System.out.println("Could not drop primary key on saad table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE Student");
catch (Exception e)
System.out.println("Could not drop Student table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE Users");
catch (Exception e)
System.out.println("Could not drop Users table: "
+ e.getMessage());
try
stmt.executeUpdate("DROP TABLE StudentUserBridge");
catch (Exception e)
System.out.println("Could not drop StudentUserBridge table: "
+ e.getMessage());
///////// Create the database tables /////////////
System.out.println("\nCreating tables ............");
// Create Stocks table with primary key index
try
System.out.println("Creating Student table with primary key index...");
stmt.executeUpdate("CREATE TABLE Student ("
+"IDNumber TEXT(8) NOT NULL "
+"CONSTRAINT PK_Student PRIMARY KEY, "
+"FirstName TEXT(50), "
+"LastName TEXT(50)"
+")");
catch (Exception e)
System.out.println("Exception creating Student table: "
+ e.getMessage());
// Create Users table with primary key index
try
System.out.println("Creating Users table with primary key index...");
stmt.executeUpdate("CREATE TABLE Users ("
+"userID TEXT(20) NOT NULL "
+"CONSTRAINT PK_Users PRIMARY KEY, "
+"FirstName TEXT(30) NOT NULL, "
+"LastName TEXT(30) NOT NULL, "
+"pswd LONGBINARY, "
+"email TEXT(30) NOT NULL, "
+"admin BIT"
+")");
catch (Exception e)
System.out.println("Exception creating Users table: "
+ e.getMessage());
// Create UserStocks table with foreign keys to Users and Stocks tables
try
System.out.println("Creating StudentUserBridge table ...");
stmt.executeUpdate("CREATE TABLE StudentUserBridge ("
+"userID TEXT(20) "
+"CONSTRAINT FK1_StudentUserBridge REFERENCES Users (userID), "
+"IDNumber TEXT(8), "
+"CONSTRAINT FK2_StudentUserBridge FOREIGN KEY (IDNumber) "
+"REFERENCES Student (IDNumber)"
+")");
catch (Exception e)
System.out.println("Exception creating StudentUserBridge table: "
+ e.getMessage());
// Create UserStocks table primary key index
try
System.out.println("Creating StudentUserBridge table primary key index...");
stmt.executeUpdate("CREATE UNIQUE INDEX PK_StudentUserBridge "
+"ON StudentUserBridge (userID, IDNumber) "
+"WITH PRIMARY DISALLOW NULL");
catch (Exception e)
System.out.println("Exception creating StudentUserBridge index: "
+ e.getMessage());
// Create one administrative user with password as initial data
String userID = "admin01";
String FirstName = "Default";
String LastName = "Admin";
String initialPswd = "admin01";
String email = "[email protected]";
Password pswd = new Password(initialPswd);
boolean admin = true;
PreparedStatement pStmt =
con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?,?)");
try
pStmt.setString(1, userID);
pStmt.setString(2, FirstName);
pStmt.setString(3, LastName);
pStmt.setBytes(4, serializeObj(pswd));
pStmt.setString(5, email);
pStmt.setBoolean(6, admin);
pStmt.executeUpdate();
catch (Exception e)
System.out.println("Exception inserting user: "
+ e.getMessage());
pStmt.close();
// Read and display all User data in the database.
ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
System.out.println("Database created.\n");
System.out.println("Displaying data from database...\n");
System.out.println("Users table contains:");
Password pswdFromDB;
byte[] buf = null;
while(rs.next())
System.out.println("Logon ID = "
+ rs.getString("userID"));
System.out.println("Last name = "
+ rs.getString("FirstName"));
System.out.println("First name = "+rs.getString("LastName"));
System.out.println("E-mail = "+rs.getString("email"));
System.out.println("Administrative = "+rs.getBoolean("admin"));
System.out.println("Initial password = "+initialPswd);
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
if (buf != null)
System.out.println("Password Object = "
+ (pswdFromDB=(Password)deserializeObj(buf)));
System.out.println(" AutoExpires = "+ pswdFromDB.getAutoExpires());
System.out.println(" Expiring now = "+ pswdFromDB.isExpiring());
System.out.println(" Remaining uses = "
+ pswdFromDB.getRemainingUses()+"\n");
else
System.out.println("Password Object = NULL!");
rs = stmt.executeQuery("SELECT * FROM Student");
if(!rs.next())
System.out.println("Student table contains no records.");
else
System.out.println("Student table still contains records!");
rs = stmt.executeQuery("SELECT * FROM StudentUserBridge");
if(!rs.next())
System.out.println("StudentUserBridge table contains no records.");
else
System.out.println("StudentUserBridge table still contains records!");
stmt.close(); // closing Statement also closes ResultSet
} // end of main()
// Method to write object to byte array and then insert into prepared statement
public static byte[] serializeObj(Object obj)
throws IOException
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
// Method to read bytes from result set into a byte array and then
// create an input stream and read the data into an object
public static Object deserializeObj(byte[] buf)
throws IOException, ClassNotFoundException
Object obj = null;
if (buf != null)
ObjectInputStream objIStream =
new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); // throws IOException, ClassNotFoundException
return obj;
} // end of class
//STLogon.java
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.sql.*;
public class STLogon extends JFrame implements ActionListener, Activator
StudentDB db;
User user = null;
String userID;
String password;
JTextField userIDField;
JPasswordField passwordField;
JButton jbtLogon;
public STLogon()
super("Stock Tracker"); // call super (JFrame) constructor
int width = 300;
int height = 100;
try{
db = new StudentDB();
catch(ClassNotFoundException ex){
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Class not found exception creating database object",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
catch(SQLException ex){
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"SQL exception creating database object",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
// define GUI components
JLabel label1 = new JLabel("User ID: ");
userIDField = new JTextField(20);
JLabel label2 = new JLabel("Password: ");
passwordField = new JPasswordField(20);
passwordField.setEchoChar('*');
jbtLogon = new JButton("Log on");
// set up GUI
JPanel userPanel= new JPanel(new BorderLayout());
userPanel.add(label1,BorderLayout.CENTER);
userPanel.add(userIDField,BorderLayout.EAST);
JPanel pswdPanel= new JPanel(new BorderLayout());
pswdPanel.add(label2,BorderLayout.CENTER);
pswdPanel.add(passwordField,BorderLayout.EAST);
JPanel buttonPanel= new JPanel(new FlowLayout());
buttonPanel.add(jbtLogon);
JPanel contentPanel= new JPanel(new BorderLayout());
contentPanel.add(userPanel, BorderLayout.NORTH);
contentPanel.add(pswdPanel, BorderLayout.CENTER);
contentPanel.add(buttonPanel, BorderLayout.SOUTH);
contentPanel.setBorder(new TitledBorder("Log on"));
setContentPane(contentPanel);
// add listeners
jbtLogon.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
try {db.close();
catch(Exception ex)
System.exit(0);
// Enable Enter key for each JButton
InputMap map;
map = jbtLogon.getInputMap();
if (map != null){
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
pack();
if( width < getWidth()) // prevent setting width too small
width = getWidth();
if(height < getHeight()) // prevent setting height too small
height = getHeight();
centerOnScreen(width, height);
public void centerOnScreen(int width, int height)
int top, left, x, y;
// Get the screen dimension
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the location for the top left corner of the frame
x = (screenSize.width - width)/2;
y = (screenSize.height - height)/2;
left = (x < 0) ? 0 : x;
top = (y < 0) ? 0 : y;
// Set the frame to the specified location & size
this.setBounds(left, top, width, height);
private boolean validUser(String userID,String password)
throws PasswordException,SQLException,IOException,ClassNotFoundException
boolean userOK = false;
user = db.getUser(userID); // get user object from DB for this ID
if(user != null)
user.validate(password); // throws PasswordException
userOK = true;
if(user.pswdAutoExpires()) // if tracking uses
db.updUser(user); // update DB for this use
return userOK;
private void doStockActivity()throws PasswordException,SQLException,
IOException,ClassNotFoundException
StockTracker f = new StockTracker(user,this,db);
f.pack();
this.setVisible(false);
f.setVisible(true);
public void activate()
this.setVisible(true);
userIDField.setText("");
userIDField.requestFocus();
user = null;
public void actionPerformed(ActionEvent e)
try
userID = userIDField.getText();
if(userID.equals(""))
JOptionPane.showMessageDialog(this,
"Please enter a valid user ID.",
"Missing User ID.",
JOptionPane.ERROR_MESSAGE);
userIDField.requestFocus();
else
password = new String(passwordField.getPassword());
if(password.equals(""))
JOptionPane.showMessageDialog(this,
"Please enter a valid password.",
"Missing Password.",
JOptionPane.ERROR_MESSAGE);
passwordField.requestFocus();
else
try
// See if userID exists and validate password
if(validUser(userID,password))
if(user.pswdIsExpiring())
JOptionPane.showMessageDialog(this,
user.getUserID()+" logon successful; "
+user.getPswdUses()+" use(s) remaining.");
if(e.getSource() == jbtLogon)
doStockActivity();
else
JOptionPane.showMessageDialog(this, "Invalid user.");
catch (PasswordExpiredException ex)
JPasswordField pf1 = new JPasswordField();
JPasswordField pf2 = new JPasswordField();
Object[] message1 = new Object[]
{"Password has expired. Please enter a new password.", pf1};
Object[] options = new String[] {"OK", "Cancel"};
JOptionPane op1 = new JOptionPane(message1,
JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, null, options);
JDialog dialog1 = op1.createDialog(null, "Change Password");
dialog1.show();
if(op1.getValue() != null && options[0].equals(op1.getValue()))
String pswd1 = new String(pf1.getPassword());
if(pswd1 != null)
Object[] message2 = new Object[]
{"Please verify new password.", pf2};
JOptionPane op2 = new JOptionPane(message2,
JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
null, options);
JDialog dialog2 = op2.createDialog(null, "Verify Password");
dialog2.show();
if(op2.getValue() != null && options[0].equals(op2.getValue()))
String pswd2 = new String(pf2.getPassword());
if(pswd2 != null)
if(pswd1.equals(pswd2))
user.changePassword(password, pswd1);
db.updUser(user);
doStockActivity();
else
JOptionPane.showMessageDialog(this,
"Both passwords are not identical.",
"Password not changed",
JOptionPane.ERROR_MESSAGE);
userIDField.setText("");
passwordField.setText("");
userIDField.requestFocus();
}// end of try
catch (PasswordUsedException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Password Previously Used. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordSizeException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Invalid password size. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordInvalidFormatException ex)
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password format. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordInvalidException ex)
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password. Try again.",
JOptionPane.ERROR_MESSAGE);
catch (PasswordException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"PasswordException.",
JOptionPane.ERROR_MESSAGE);
catch (IOException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"IOException.",
JOptionPane.ERROR_MESSAGE);
catch (SQLException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"SQLException.",
JOptionPane.ERROR_MESSAGE);
catch (ClassNotFoundException ex)
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"ClassNotFoundException.",
JOptionPane.ERROR_MESSAGE);
public static void main(String[] argv)
final STLogon f = new STLogon();
f.setVisible(true);
//StudentDB.java
import java.io.*;
import java.sql.*;
import java.util.*;
public class StudentDB
private Connection con = null;
// Constructor; makes database connection
public StudentDB() throws ClassNotFoundException,SQLException
if(con == null)
String url = "jdbc:odbc:saad";
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(ClassNotFoundException ex)
throw new ClassNotFoundException(ex.getMessage() +
"\nCannot locate sun.jdbc.odbc.JdbcOdbcDriver");
try
con = DriverManager.getConnection(url);
catch(SQLException ex)
throw new SQLException(ex.getMessage()+
"\nCannot open database connection for "+url);
// Close makes database connection; null reference to connection
public void close() throws SQLException,IOException,ClassNotFoundException
con.close();
con = null;
// Method to serialize object to byte array
private byte[] serializeObj(Object obj) throws IOException
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
// Method to deserialize bytes from a byte array into an object
private Object deserializeObj(byte[] buf)
throws IOException, ClassNotFoundException
Object obj = null;
if (buf != null)
ObjectInputStream objIStream =
new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); //IOException, ClassNotFoundException
return obj;
// Methods for adding a record to a table
// add to the Student Table
public void addStudent(String IDNumber, String FirstName, String LastName)
throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO Student VALUES ('"
+IDNumber+"'"+",'"+FirstName+"'"+",'"+LastName+"')");
stmt.close();
// add to the Users table
public boolean addUser(User user) throws SQLException,IOException,
ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) == null)
dbLastName = user.getFirstName();
dbFirstName = user.getLastName();
Password pswd = user.getPassword();
// dbemail = user.getEmail();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement(
"INSERT INTO Users VALUES (?,?,?,?,?,?)");
pStmt.setString(1, dbUserID);
pStmt.setString(2, dbFirstName);
pStmt.setString(3, dbLastName);
pStmt.setBytes(4, serializeObj(pswd));
// pStmt.setString(5, dbemail);
pStmt.setBoolean(5, isAdmin);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User exists - cannot add.");
return result;
// add to the UserStocks table
public void addStudentUserBridge(String userID, String IDNumber)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO StudentUserBridge VALUES ('"
+userID+"'"
+",'"+IDNumber+"')");
stmt.close();
// Methods for updating a record in a table
// updating the Users Table
public boolean updUser(User user) throws SQLException,IOException,
ClassNotFoundException
boolean result = false;
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
dbUserID = user.getUserID();
if(getUser(dbUserID) != null)
dbLastName = user.getFirstName();
dbFirstName = user.getLastName();
Password pswd = user.getPassword();
// dbemail = user.getEmail();
isAdmin = user.isAdmin();
PreparedStatement pStmt = con.prepareStatement("UPDATE Users SET FirstName = ?,"
+" LastName = ?, pswd = ?, email = ?, admin = ? WHERE userID = ?");
pStmt.setString(1, dbFirstName);
pStmt.setString(2, dbLastName);
pStmt.setBytes(3, serializeObj(pswd));
// pStmt.setString(4, dbemail);
pStmt.setBoolean(4, isAdmin);
pStmt.setString(5, dbUserID);
pStmt.executeUpdate();
pStmt.close();
result = true;
else
throw new IOException("User does not exist - cannot update.");
return result;
// Methods for deleting a record from a table
// delete a record from the Student Table
private void delStudent(String IDNumber)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM Student WHERE "
+"IDNumber = '"+IDNumber+"'");
stmt.close();
// delete a record from the Users Table
public void delUser(User user) throws SQLException,IOException,
ClassNotFoundException
String dbUserID;
String stockSymbol;
Statement stmt = con.createStatement();
try {
con.setAutoCommit(false);
dbUserID = user.getUserID();
if(getUser(dbUserID) != null) // verify user exists in database
ResultSet rs1 = stmt.executeQuery("SELECT userID, IDNumber "
+"FROM StudentUserBridge WHERE userID = '"+dbUserID+"'");
while(rs1.next())
try
stockSymbol = rs1.getString("IDNumber");
delUserStocks(dbUserID, stockSymbol);
catch(SQLException ex)
throw new SQLException("Deletion of user student failed: "
+ex.getMessage());
} // end of loop thru UserStocks
try
{ // holdings deleted, now delete user
stmt.executeUpdate("DELETE FROM Users WHERE "
+"userID = '"+dbUserID+"'");
catch(SQLException ex)
throw new SQLException("User deletion failed: "+ex.getMessage());
else
throw new IOException("User not found in database - cannot delete.");
try
con.commit();
catch(SQLException ex)
throw new SQLException("Transaction commit failed: "+ex.getMessage());
catch (SQLException ex)
try
con.rollback();
catch (SQLException sqx)
throw new SQLException("Transaction failed then rollback failed: "
+sqx.getMessage());
// Transaction failed, was rolled back
throw new SQLException("Transaction failed; was rolled back: "
+ex.getMessage());
stmt.close();
// delete a record from the StudentUserBridge Table
public void delUserStocks(String userID, String stockSymbol)
throws SQLException,IOException,ClassNotFoundException
Statement stmt = con.createStatement();
ResultSet rs;
stmt.executeUpdate("DELETE FROM StudentUserBridge WHERE "
+"userID = '"+userID+"'"
+"AND IDNumber = '"+stockSymbol+"'");
rs = stmt.executeQuery("SELECT IDNumber FROM StudentUserBridge "
+"WHERE IDNumber = '"+stockSymbol+"'");
if(!rs.next()) // no users have this stock
// delStock(stockSymbol);
stmt.close();
// Methods for listing record data from a table
// Ordered by:
// methods that obtain individual field(s),
// methods that obtain a complete record, and
// methods that obtain multiple records
// Methods to access one or more individual fields
// get a stock description from the Stocks Table
public String getStockDesc(String stockSymbol)
throws SQLException, IOException, ClassNotFoundException
Statement stmt = con.createStatement();
String stockDesc = null;
ResultSet rs = stmt.executeQuery("SELECT IDNumber, name FROM Student "
+"WHERE IDNumber = '"+stockSymbol+"'");
if(rs.next())
stockDesc = rs.getString("IDNumber");
rs.close();
stmt.close();
return stockDesc;
// Methods to access a complete record
// get User data from the Users Table
public User getUser(String UserID) throws SQLException, IOException,
ClassNotFoundException
Statement stmt = con.createStatement();
String dbUserID;
String dbLastName;
String dbFirstName;
Password dbPswd;
String dbemail;
boolean isAdmin;
byte[] buf = null;
User user = null;
ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE userID = '"
+UserID+"'");
if(rs.next())
dbUserID = rs.getString("userID");
dbFirstName = rs.getString("FirstName");
dbLastName = rs.getString("LastName");
dbemail = rs.getString("email");
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
dbPswd = (Password)deserializeObj(buf);
isAdmin = rs.getBoolean("admin");
user = new User(dbUserID,dbFirstName,dbLastName,dbPswd,isAdmin);
rs.close();
stmt.close();
return user; // User object created for userID
// Methods to access a list of records
// get list of selected fields for all records from the Users Table
public ArrayList listUsers() throws SQLException,IOException,
ClassNotFoundException
ArrayList aList = new ArrayList();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT userID, FirstName, LastName, admin "
+"FROM Users ORDER BY userID");
while(rs.next())
aList.add(rs.getString("userID"));
aList.add(rs.getString("FirstName"));
aList.add(rs.getString("LastName"));
aList.add(new Boolean(rs.getBoolean("admin")));
rs.close();
stmt.close();
return aList;
// get all fields in all records for a given user from the Userstocks Table
public ArrayList listUserStocks(String userID) throws SQLException,IOException,
saaddani wrote:
No information popped up in the console window before, during, or after the error was given. The program compiled and ran and therefore no error information was provided in the complier window either.
If I am missing what you are asking then please provide instructions as to how to find this error information. You are posting the error message for the exception but not printing the stack trace.
Far as I can tell you are printing more information with each exception (for example "Exception creating Users table") but you did not post what that was, that info would localize the problem.
As a guess the problem is when you extract the fields via the query. You are using named values rather than indexes and you use "select *" rather than specifically naming the columns. Some databases (for example Oracle), require that using names must be in exactly the same order as the query returns them. You have no idea what that order is because you use "select *"
Finally it would be a LOT easier if you wrote classes that did nothing but the database operations. NO GUI CODE. You then test that code to make sure it works. Once that code works then you write gui code which uses those classes. Besides making it easier to understand you are also more likely to get assistance since there is less code to look at.
Maybe you are looking for
-
Problem with Filtering Data by Using "Greater Than" in APD
Dear Experts, First of all, I am a novice of SAP Data Mining. I try to filter data in APD by using the 'Restrict Amont of Data (the Filter Icon).' My problem is really simple. I don't know how to filter data which have value greater than a constant
-
Dynamic Dimesion Building using SQL Interface
I am attempting to use SQL Interface in Essbase 6.5 to dynamically build the account dimension from a PeopleSoft tree. The view works fine in SQL worksheet, but the last UNION statement does not work using the SQL interface. Here is the SQL that is g
-
MM: SUBCONTRACTING PROBLEM
Hi all , here is a typical problem i am facing " i am not able to make Sub contracting PR against asset or Cost center we have entered all the data. But the messege flashed is "Combination Item category L and Account assignment category A not def
-
Can I use L2TP without IPSec in Tiger?
Hello. Can I use built-in L2TP VPN Client without IPsec support? i don't need ipsec encrypt, i just need l2tp tunneling. if i cannot use with built-in tiger l2tp client, could you recommand the software that i can do this? thanks..
-
Hello, I am sending some byte array by portions of 255 bytes to my on-card Applet using a sequence of APDU command-response operations. I just wanted to know, in case there is any possibility to make on-side chaining: send some sequence of APDU comma