Multiple query results in HashMap

Hi,
Can anybody tell me how I can store multiple results of a select query in a HashMap. I basically know how to do it but here is the problem:
I want the table ids to be the keys and ArraySets containing database data to be the values of the HashMap. But whenever I add a new key/value pair to the HashMap all the values get overridden with the ArraySet I add.
Here is my code:
public HashMap getResults() throws Exception {
Class.forName(org.gjt.mm.mysql.Driver);
Connection con = DriverManager.getConnection(jdbc:mysql:///myDbName?user=user&password=password);
HashMap hmResults = new HashMap();
ArrayList alValues = new ArrayList();
PreparedStatement preparedStatement = con.prepareStatement("select id, name, email from mytable");
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
alValues.clear();
alValues.add(resultSet.getString("id"));
alValues.add(resultSet.getString("name"));
alValues.add(resultSet.getString("email"));
// the next line adds the correct key and value but also overrides all the other values in the HashMap, why?
hmResults.put(resultSet.getString("id"), alValues);
return(hmResults);
The method above returns a HashMap containing the correct keys but the values are all the same.
What am I doing wrong?
Thanks for helping me out!

Because your adding to the HashMap a reference to that ArrayList, not the ArrayList itself. So basically each key in your HashMap references the one ArrayList, which you repeatedly clear and update. In the end, all your keys map to the same reference, which will contain the very last information retrieved from the ResultSet.
Simple fix... place the ArrayList alValues = new ArrayList() line inside your loop, and each key will be mapped to a different reference.

Similar Messages

  • Multiple Query Result tabs

    Is it possible to have a new Query Result tab opened every time a query is run instead of overwriting the current contents of the window Query Result tab?
    thanks,
    Louis

    Hi Louis,
    Welcome to the forum. Here is a thread with some posts telling you how to control this, both for Query Results and the Object Viewer:
    Re: SQL Developer no longer letting me look at the same table name on 2 servers
    Regards,
    Gary

  • Bug in pinning of results tabs results in multiple query results tabs

    In Tools > Preferences > Database > Worksheet there is an option called Automatically Freeze Reult Tabs.
    This option, when unchecked, does not seem to be working. New query results tabs are created when pressing F9 to run selected query text.
    Elsewhere I have read that this is a known bug (9247525). A work-around is said to be to not select text before pressing F9. However, this does not seem to always work for me. Sometimes SQL Developer tries to execute code that is outside of the immediate query. The result is usually a query error.
    Thus a whole bunch of query result tabs build up.
    Is this bug being addressed? Is there a place where these bugs can be looked up? Or that status of a bug checked?
    Thanks for any assistance.
    (I am on 2.1.0.63. On Windows.)
    --Michael                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    The bug you have found will be somewhere in the list of work for the SQL Developer team and should get fixed and included in a public release/patch eventually.
    It sounds like your issue with the workaround (statement being identified based on cursor position) is with SQL Developer's pickiness with what is the end of a statement. As a general rule, SQL Developer will only consider a ; at the end of a line or a / starting a new line as the end of a statement - it does not consider a blank line the end of a statement. For example, the following is all considered a single statement:
    select * from dual
    select * from dual;theFurryOne

  • Text File From Multiple Query Results

    SQL Server 2018 R2
    I need to create a text file to send to another company. The file contains 4 main parts: File Header, Master Records, Record Details and File Footer. There can be multiple Master Records and multiple Record Details associated with each Master Record.
    The file should look something like this:
    File Header
    Master Record
    Record Details
    Record Details
    Master Record
    Record Details
    Master Record
    Record Details
    Record Details
    Record Details
    File Footer
    Each line type contains multiple columns that need to be separated with a “|” symbol.
    I can write the queries that will return each record type in the correct order by using a loop. However I don’t know how to get them into a single text file in that order.
    Please avoid solutions that use xml unless it properly takes into account the possibility of special symbols in my data.
    Any help would be appreciated.

    Thanks for the reply.
    I had considered your solution already and found an article explaining the same thing. The problem with it is that I would somehow have to create a loop that would create and combine the files in the right order instead of just three files in a set order.
    That is beyond my current knowledge.
    I have found a messy way of combining all the record types into a single query in the correct order. Using that I should be able to easily export it into a text file. I don't really like my solution but it should work.
    Thanks,
    Scott

  • Splitting  single row to multiple query result

    Hi All,
    I have a column is a table with data seperated by new like . I need to write a select query which can split this to multiple rows .. can any one help me out .
    please see the xample
    select data_comm from customer where rownum=1
    data_comm
    serial=0
    parallel=1
    comm=1
    a single row contain a field called data_comm which has got data stored seperated by new_line
    I need to write a query which can split data on data_comm and give as multiple rows.
    Thanks in advance

    I think something like this would do the trick.
    Part 1:
    select substr(data_comm, 1, instr(data_comm,chr(10),1)) from customer ;
    Part 2:
    select substr(data_comm,instr(data_comm,chr(10),1)+1,instr(data_comm,chr(10),2)) from customer ;
    Part 3:
    select substr(data_comm,instr(data_comm,chr(10),2)+1,instr(data_comm,chr(10),3)) from customer ;
    Maybe the chr(10) is not the used newline char, but you can figure that one out yourself

  • Unable to display results of multiple query in grid in Oracle SQL Developer

    Hi, I am a newbie to this forum and couldn't find the Oracle SQL Developer forum so posting it here.
    My question: How to display multiple query results in grid in Oracle SQL Developer.
    Example:
    select * from Employee;
    select * from Department;
    - when I select both the queries and hit F5 in Oracle sql developer. By default it displays in output window.
    - How to display result of both the queries in Grid.
    Any thoughts on this would be really helpful.
    Thanks in advance.
    Harsh

    Hi Harsh,
    I'd say that the Results grid is designed to only show the results of 1 query at a time. I don't know/can't see how it would display multiple queries at a time.
    I would suggest either joining your tables to create a single query or opening another SQL Worksheet for one of the queries so that you can display the results side-by-side.
    Maybe you could explain what you're trying to do. Why are you trying to display multiple results in the same query grid?

  • How to display MySql query results in multiple columns?

    Hi, I know how to display PHP/MySq
    l query results in a single column, but I am really stuck at displa
    ying the results in multiple columns in DW CS4.
    Can anyone help me with a code example?. I am new to php/mysql. Thanks

    Are you asking how to pivot the results of the query? Do a search for horizontal looping. If that's not what you are asking, please provide more details.

  • Sending email using PL/SQL based on a query result

    Hello all,
    I want to create a procedure using PL/SQL, based on a query result.Here is the scenario:
    I have multiple tables in Target and Source databases that I want to compare(not the whole table but queries on these tables) and if they differ, I want to shoot an email. I have some ideas how to implement this but not sure whether it is the best approach.
    select Acct_id, total from SourceTableA
    minus
    select Acct_id, total from TargetTableA
    select Acct_id, sum from SourceTableB
    minus
    select Acct_id, sum from TargetTableB
    If the result of any of above queries > 0 then I want to shoot an email and want to repeat this procedure in the morning every day.
    I know how to implement send_mail procedure using UTL_SMTP package and how to schedule tha job by dbms_job package. But I am not sure how to implement the result of minus query. In case if minus > 0 then I also want to send the name of tables in the email message where source and target tables are not same. Should i use cursor, variable or insert the result in a new table? any help would be highly appreciated. Thanks in advance.
    Khan

    Actually these queries are the part of our daily testing that we run everyday manually(after the scheduled ETL load) to see if there are any discrepencies between our datawarehouse tables and source tables. So instead of running these queries manually everyday we want to schedula a procedure that will shoot an email in case of any discrepency and indicate which tables have problems.

  • Export query result to csv using Export Wizard

    Been a decade since I last used Oracle and related tools.
    I had to use Oracle server again, I have a query over multiple tables, I am to run a scheduled script that will spit out the query result as a csv file.
    I started with SQL Developer Export wizard, in step "Specify Data", I am at a loss, where to specify the query itself? I see a Name,Schema,Type input, a text area below, Up,UpAll,Down,DownAll buttons etc etc. Where do I specify my query here? Can someone please help?
    Is this the best way to go about to schedule a data export (query to csv) daily?

    To export a user query rather than a whole table, run it in a worksheet and export using the context menu on the result grid. However none can be scheduled.
    Instead you can look at the SPOOL command and schedule it through SQL*Plus. Any questions can go to the iSQL*Plus and/or SQL And PL/SQL forum.
    Have fun,
    K.

  • Query result to ASCII file output

    Seems like there SHOULD be some rediculously simple solution
    to this - but I sure haven't found it yet! I have a query which
    produces the a varying number of columns (based on a multi-select
    cfselect) which I need to output to a comma delimited ASCII (.TXT
    or .DAT or .CSV file). I have all the steps worked out when the
    number of columns and their names are known, but I need to make
    this variable. First choice would be to be able to just "DUMP" the
    query result into a text file. CFDUMP can send results to a text
    file, but NOT in comma delimited format, and with all kinds of info
    besides just the basic data. (NOT good!) Second choice, since the
    "append to text file" uses an output property that expects a comma
    delimited string variable would be to use CFLOOP to loop thru the
    rows in the query and put them (a row at a time) into a variable,
    then use that variable for the file append. Problem is I can't find
    a way to just say "send *ALL* to the string variable. Every example
    I have been able to find includes specifying the column NAMES when
    doing anything with a row in the query result!!! Short of a brute
    force series of if/then statements that specify EACH POSSIBILITY
    (in this case 60 - 75 of them, and the number WILL GROW!) I haven't
    been able to find a solution. There's GOTTA BE A WAY!!!!! :)

    auntiealias
    > I tried that, but as far as I could figure you still
    have to have a specific column name
    Look at the udf more closely. If you read the documentation
    it states all of the parameters are optional, except the query. So
    if you do not supply column names, the function will use the
    columnList variable to determine the names of the columns in the
    query. If you look at the actual code, notice it uses array
    notation to extract the values (not evaluate) .
    ... (code to create query) ...
    <!--- pass in the query object only ---->
    <cfset test = QueryToCSV2( data )>
    http://cflib.org/index.cfm?event=page.udfbyid&udfid=1197
    > I have a cfselect with multiple set to "yes" and the
    selections are "which columns of
    > data do you want to see?"
    Hopefully you are not using the raw form value directly in
    your sql, because that is a sql injection attack just waiting to
    happen.

  • Transferring multi-column query result into MS Excel

    Hello everybody!
    An ultimate novice in Oracle, with some database concepts, is here.
    The very first challenge; which I encoutered is that I want to transfer a Select query result, with multiple columns, into MS Excel sheet in a way that each field occupies a separate column in the sheet.
    I hope the forum members will show me a simple way to get around the problem.
    Thanks in anticipation.
    Rabi

    what will happen the query returns too many rows that
    Excel cant hold? I faced this problem and divided the
    report into "n" numbers based on the number of rows
    returned. Is there any internal logic for it in
    oracle?Excel is capable of holding 65536 rows of data on a sheet.
    Oracle is capable of writing data out to files.
    Oracle does not know or care whether the file it is writing is for Excel or any other product, as the file you are likely to be writing is CSV (comma seperate format) which is an open format, not specifically for Excel. If you need to limit the number of rows per CSV file then you will have to code this "business logic" into your code that produces the CSV file from Oracle.

  • During SQL query inserting a record - will it appear on the query result

    Hi,
    Oracle 10g SELECT-query executes ca 10 seconds and contains Joins over multiple tables in on database conenction.
    On execution 3rd second a new record is inserted in another database connection and commited to the database, the 3rd query satisgy the SELECT-Query fileters.
    Wil lthe inserted record on 3rd second appear on the query results?
    Thx.

    CharlesRoos wrote:
    Hi,
    Oracle 10g SELECT-query executes ca 10 seconds and contains Joins over multiple tables in on database conenction.
    On execution 3rd second a new record is inserted in another database connection and commited to the database, the 3rd query satisgy the SELECT-Query fileters.
    Wil lthe inserted record on 3rd second appear on the query results?
    Thx.In general Keith is right and a select will not see changes done and committed in a different session, that happend during the select. This is called READ CONSISTENCY. THis means a select will see the data from the exact time when it was called.
    However with database links in place read consistency can not be fully garanteed.
    See this explaination and solution from the 10g docs : http://docs.oracle.com/cd/B19306_01/server.102/b14231/ds_txnman.htm#i1008473

  • Odac 12.1 Oracle.VsDevTools Cannot edit query results

    I am running Windows 7 64-bit and Visual Studio 2010
    I installed ODTwithODAC121010 successfully.
    In Visual Studios Help>About it shows: Oracle Developer Tools for Visual Studio 12.1.0.1.0
    Issue:
    After updating to odac 12.1 I can no longer edit/insert data into the query builder results pane.
    I have relied on this capability in previous versions of odac.
    Has this feature been removed?
    I've connected to multiple Oracle 11g dbs with same results below:
    I get the following response when I attempt to edit a field in the query results pane:
    No row was updated.
    The data in row 10 was not committed.
    Error Source: .
    Error Message: Unable to parse expression.
    Correct the errors and retry or press ESC to cancel the change(s).
    I get the following response when I paste a new row in the query results pane:
    No row was updated.
    The data in row 11 was not committed.
    Error Source: Oracle.VsDevTools.10.0.
    Error Message: Object reference not set to an instance of an object.
    Correct the errors and retry or press ESC to cancel the change(s).
    Is there something I need to do to enable this?
    What are some good alternatives if this capability is no longer supported?

    Hi George Pertea,
    Thanks for the reply.
    I am in the edit query mode and also the query tool bar is enabled.
    But my "view sql" button is disabled,I cannot click on it.
    I am logged in as "Admin" , so what is the problem.
    I was able to do that in XI R2 before.
    Please help me!
    Thanks

  • How to save query result in excel file

    Hi all,
    How to save query result in excel file from sql*plus tool.
    thank you

    Do you really need an Excel file (binary) or a simple CSV?
    If you just need a CSV then search for DUMP_CSV at http://asktom.oracle.com or at this forum
    If you need formatting and/or multiple worksheets then you can use free tools like
    https://xml-spreadsheet.samplecode.oracle.com/ or https://exceldocumenttype.samplecode.oracle.com/
    Regards
    Marcus

  • WIS 00015 error- Multiple Query Filters contain a prompt with same name

    Hi
            I am working BOXIR2 environment. I created two prompts at Universe level- one of Date field and one on agency name field.
    syntax for the prompts is
    customerInfo.RSRCE_NAME =  @Prompt('Enter value(s) for AgencyName ','A' , , ,)
    datetable.STARDATE =datetable.STARDATE.STARTDATE =  @Prompt(' 'Enter value(s) for StartDate:','D' , , ,)
    When I include even one of  the prompts in the report I am getting an error WIS 00015 Multiple Query Filters contain a prompt with the same text, but the prompts use a different operand type.
    If I try to change text of one of the prompts in Universe selection statement, then I see the prompt two times in the report.
    Please let me know how to overcome this issue.

    Ok, I've simplified the case.
    Here is the real case :
    Object filter =
    Based on object =
    .[LEVEL01]
    Object filter =
    Based on object =
    .[LEVEL01]
    In WBI query result I take these objects :
    .[LEVEL01]
    .[LEVEL01]
    .[4IUX93YJGXQEHGLX0T0GPNA9Y]
    In query filters, my 2 filters with same text :
    1.
    I run the query.
    Answer to question 'Single Year Period ?' = Period 06 2010
    ==> MDX error
    A database error occured. The database error text is: Echec de l'exécution de la requête MDX SELECT  { .[4IUX93YJGXQEHGLX0T0GPNA9Y] }  ON COLUMNS , NON EMPTY CROSSJOIN( .[LEVEL01].MEMBERS, .[LEVEL01].MEMBERS ) DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS FROM SAP VARIABLES INCLUDING .[Z12010006] INCLUDING .[Z12010006] avec l'erreur Invalid MDX command with . (WIS 10901)
    And you can see that the value sent to both filters is the same and come from the first filter .[Z12010006] instead of applying the value to each filter .[Z12010006] for the first one and .[Z12010006] for the second one.
    Please, notice that if I change the order of this 2 filters in the WBI query, the MDX generated become :
    SELECT  { .[4IUX93YJGXQEHGLX0T0GPNA9Y] }  ON COLUMNS , NON EMPTY CROSSJOIN( .[LEVEL01].MEMBERS, .[LEVEL01].MEMBERS ) DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS FROM SAP VARIABLES INCLUDING .[Z12010006] INCLUDING .[Z12010006]
    Thanks for your help.
    G.OM.

Maybe you are looking for

  • Battery checks say change battery, but it charges and works fine. Help?

    Hey there, Just having a problem with my Laptop battery. My product type is a HP G61 Notebook PC. The battery icon in the bottom left says the battery should be replaced, with checks saying it has reached the end of it's useful life. I find this hard

  • Connected bluetooth headset to Macbook, but no audio

    Hey. I successfully connected my Jabra bluetooth headset to my Macbook. In System Preferences -> Sound, I selected the headset device for both my input and output. The input seems to work, but the output does not work at all. For output, it says "The

  • Why can't I see the social media widgets in Firefox?

    I have noticed that the social media widgets "follow" on both FB and Twitter seem to show up fine in Chrome but fail to appear in Firefox. What can I do to rectify this?

  • Problem with adf tables in dynamyc region

    Hello. I have a problem when use ADF tables within dynamic regions. It happens that if the table is inside the first task flow that is loaded (by default) in the dynamic region, retrieves the data perfectly, but if the table is in a second, third and

  • Trying to download Digital Copy of a movie

    Ok well I bought a new movie which came with a digital copy of the movie, for some reason I can not get to the web page to put the code in. I have a internet connection, and it will work on a dell. Is there any reason or another way to do this.