Shall I use global or local variables for my program?

Hello,
1) I am using 2 while loops in parallele. One 50 ms timed and the other one 1000 ms. The 50 ms one gets data from a sensor. I want to display that data every 1000ms in the 1000 ms loop. I have used global variables to do that. Should I better use local variables?
2) This question deals with the VI I have attached
a)  Shall I initialise the "  Quitter programme " global variable in the main VI aswell ? Or is what I have done enough?
b)
I want the sequence to continue ( finishes the last sequence and goes back to the first one without any delay if possible ) until the user presses Quit. I am concerned about the " wait until " icon of the exterior main while loop ( set to be 250 ms at the moment ). This time, 250 ms, is the time it takes between the end of the last sequence and the beginning of the first sequence? Is that right? Once u start the first sequence, the while loop doesn’t do anything until the end of the last sequence ( my 3 sequences can take several minutes ) ?
Hope I am clear… lol
Don’t hesitate to ask any questions if not clear enough
thanks a lot,
David
Attachments:
Example1.zip ‏28 KB

Bonjour Marc.  You will definitely have a race condition because you are writing to the global in a parallel loop.  You could click the stop button in the quitter program, then before it is read in the main loop, the lower loop writes a false to it, and your click is lost.  Why do you want a separate quitter program?  You may have a good reason but it isn't clear here.  I would not use globals or locals for this, just put your stop button on the main vi.  You already have one, so why do you want another one in another vi?  If you must do it this way, eliminate both lower loops.  They are not necessary.  The global default is set to false, so when you run the vi, it is false.  The button mechanical action is set to latch when released, so after clicking it will turn true until the main vi reads it, then it will automatically turn false.  So you don't need the lower loops to keep writing false to it.  If you just eliminate both lower loops, it will work fine.  The only purpose I could see for the quitter vi is to have one button cause several vi's to stop.  Instead of doing it this way, put one stop button in your main vi, create a reference (right click - create - reference), and wire this reference into all subvi's that the main calls.  The subvi's must be changed to accept the reference and use it.  This would be a much better method to close all vi's with one button.
You could also get rid of the sequence structure (it hides code and makes it more difficult to read).  Just put all your code side by side.  The error in/out wire will ensure that the execution order will be fixed, just like in your first sequence with the open file and write file functions.  Just wire the error out of the write vi to the second write vi, and then the error out of the second write vi to the close vi.  No sequence structure needed, and all your code is viewable on one screen.
- tbob
Inventor of the WORM Global

Similar Messages

  • Global and Local Variable

    Hi Gurus, I was unable to see where I can define local and global variables? I see that help.sap.com documentation but where do I create. All variables that I create, are global because, they are visible to all and they all can use it? Any help would be greatly appreciated.

    As far as I know, Variables are re-usable objects that are not dependent upon InfoProvider. When I look at this link
    http://help.sap.com/saphelp_nw04/helpdata/en/5c/8db07d555411d189660000e829fbbd/frameset.htm
    it talks about Global and Local variable? Is this different than what we use in Query Designer?

  • Is This a Global Versus Local Variable Problem?

    I intend to use a variable (myselector) with a text value (e.g. roses, Big Sur, Pacific Grove, night, etc.) for the sort criteria of my photography list.  Selection of a tab from a Tabbed Panel will appropriately define the variable and the selected thumbnails will display in the Content Panel.
    The variable "myselector" is defined in the head section; a function for each tab of the Tabbed Panel will redefine the variable per the selected tab.  Within the function, I am not using "var" to call the variable.  Though the variable "myselector" should be global, the changes to its value are discarded when the function closes.  This indicates that it is functioning like a local variable in the function.  After a bit of reading, I've not found the cause of the global/local discrepancy or a fix for it.
    Diagnosis History - I generated a simplified code.  Variable "myselector" is defined as "abcd"; function "myfilter" is called by onclick of the text "button" and changes "myselector" to "efgh".  At the end of the file, I used "document.write (myselector) to output the "myselector" value.  The script follows.
    The end value of "myselector" does not change.  However, when I add "document.write (myselector)" to the function, then the changed value is displayed.
    I ask someone to explain what I am doing incorrectly or, at least, guide me to a solution.  I thank you for your assistance.
    Scott
    <script type="text/javascript">
    var myselector="abcd";
    function MM_callJS(jsStr) { //v2.0
      return eval(jsStr)
    </script>
    </head>
    <body>
    <div id=text>
    <p onclick="MM_callJS('myfilter();')">Button</p>
    <script type="text/javascript">
    function myfilter() {myselector="efgh"; }
    </script>
    <script type="text/javascript">
    document.write (myselector);
    </script>
    </div>

    Dear Ben:
    I thank youfor your patience.  This includes the script using Insert - Syntax Highlighting - Java.
    The coding needs a lot of clean up but I want it to work, first.
    Scott
    <script src="SpryAssets/xpath.js" type="text/javascript"></script>
    <script src="SpryAssets/SpryData.js" type="text/javascript"></script>
    <script src="SpryAssets/SpryTabbedPanels.js" type="text/javascript"></script>
    <script type="text/javascript">
    var dsphotodata = new Spry.Data.XMLDataSet("EM_photo.xml", "/gallery");
    </script>
    <script  type = "text/javascript">
    function MM_callJS(jsStr) { //v2.0
      return eval(jsStr)
    </script>
    <script type="text/javascript">
    var dsphoto = new Spry.Data.XMLDataSet("EM_photo.xml", "/gallery/photos/photo");
    dsphoto.filter(subjectfilter);
    var myselector;
    </script>
    <link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    This is a test of Scott's efforts to program his website.
    <br />
    <br />
    <div id="TabbedPanels1" class="TabbedPanels">
      <ul class="TabbedPanelsTabGroup">
        <li class="TabbedPanelsTab" tabindex="0" onclick="MM_callJS('{myselector=\'animal\'}; subjectfilter(); dsphoto.filter(subjectfilter); ')">Tab 1</li>
        <li class="TabbedPanelsTab" tabindex="0" onfocus="MM_callJS('myselector=\&quot;pgbeach\&quot; subjectfilter(); dsphoto.filter(subjectfilter); ')">Tab 2</li>
        <li class="TabbedPanelsTab" tabindex="0">Blank</li>
    </ul>
      <div class="TabbedPanelsContentGroup">
        <div class="TabbedPanelsContent" >Content 1
          <br />
    <br />
    <script> {document.write (myselector)} </script>
          <br />
          <div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
        </div>
        <div class="TabbedPanelsContent">Content 2
          <script> {document.write (myselector)} </script>
          <br />
          <div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
        </div>
        <div class="TabbedPanelsContent">Content 3  <script> {document.write (myselector)} </script><br />
    <div spry:region="dsphoto dsphotodata"> <img src="{dsphotodata::thumbnail/@base}{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px spry:repeat="dsphoto" onclick="dsphoto.setCurrentRow('{ds_RowID}');" /></div>
    </div>
    </div>
    </div>
    <div id="Selected_Photo" spry:detailregion = "dsphoto dsphotodata"  >
    <img src="Photo-Thumbnails/{@thumbpath}" width = {@thumbwidth}px height = {@thumbheight}px /><br />
    <img src="Photo-Email/{@path}" width = {@width}px height = {@height}px />
    </div>
    <script type="text/javascript">
    var subjectfilter = function(dataSet, row, rowNumber, criteria) { if (row["@subject"].search (myselector) != -1) return row; return null; };
    <!--
    var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1", {defaultTab:2});
    //-->
    </script>

  • Local variable for an Array of fixed size

    Hello,
    I have a two multirate loops in a VI. 
    In one loop, I want to refer an fixed sized array initialized in the other loop.
    But I coudn't name the array, so I can't refer it.
    Is there any way to refer it?
    Thanks,
    Young.

    If you need a local variable, there is no other way than to create an indicator for it.
    In LabVIEW there is no "fixed length" array : you can always add or remove an array element, and you don't need to declare it as in other languages. They are intrinsic dynamic objcets. Of course, the memory manager has to cope with this, that's why it's often better to initialize an array, to give it its final size immediately, resulting in faster running programs. However, this is only noticeable with relatively large arrays (> 10000-100000 elements).
    May be you should explain in more details what you intend to do, because trying to reproduce a C approach in LV is probably not the best thing to do. For instance, you said that you are initializing your array in a first loop. You mean that you re-initialize the array at each iteration ? I suppose no, so may be you could put the initialize step out of the loop, and wire the array to your two parallel loops.
    Remember also that local variables are not always good programming solutions, since using them will generate copies of their content each time they are refered to. And that can low down your program very significantly...
    Message Edité par chilly charly le 11-05-2005 05:05 PM
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • Local variables for clean code

    A question of style and LV correctness: 
    I'm quite aware of the risks of these guys, but I see no option here. Right now I have a program with ~35 events in an event structure. I have a wire that contains many device settings that only 2 of these events can change. About 6 events in total require the use of the data on this wire.
    Now, I see two choices:
    1) I can use a shift register and drag the stupid wire across 35 frames and then remember to do it in any additional frames when I add more
    2) I can use a local variable.
    This seems much, much cleaner to me, and I see no better way of doing it. My question is, is there? I've looked up feedback nodes, but I think I can only use them in single event cases. Their data doesn't seem accessible beyond one event case. is there some better option? The data on the wire is an array of objects (classes), if that helps. 

    pobrepablo1 wrote:
    Still though, I object on principle to having a wire across every one of my diagrams, it's cluttersome .
    I thought of a compromise, how about I use a shift register but wire it around my event structure, through a case structure breaking the wire only when I need to? i.e. see attached
    So a single thin 1D object across all event cases is more cluttersome than an additional external 2D case structure, partially wired extra tunnels, and all the extra convoluted logic holding it all together? You priorities seem to be biased.
    A nice wire across all cases is much better. It can be read and written in any event case that needs to, and can always be found in exactly the expected location. Remember that a shift register is very efficient. If the data size does not change, it operates fully in place for the duration of the run. It also often contains data that is not directly of interest to the operator so it does not need a display. A local variable requires a front panel object that needs to be updated in the UI thread. In needs a data copy in memory memory for the control/indicator itself as well as another copy for the transfer buffer (because the FP update is asynchronous). Then we have a third copy in the wire itself. Than makes it three copies of your potentially large array. Add another copy for each local variable instance, and you probably end up using 10x more memory compared to a simple shift register. It all adds up!
    Local variables can be placed anywhere and keeping track of them is like herding cats. The next programmer to work on your project will have a hard time tracking them all down. In properly designed code, it is just "follow the wire". Much more clear and almost self documenting.
    LabVIEW Champion . Do more with less code and in less time .

  • CIsco ISE use two different local certificates for EAP

    Hi Experts,
    ISE 1.2.1.198
    It is possible to use two different local certificates on cisco ISE, generated by two different root CA, for EAP?
    Example:
    1 - Microsoft CA for notebooks
    2 - Different CA (public, openssl, other) for mobiles
    And, in case it is possible, which will be the first one presented from the server to the client for EAP-TLS authentication?
    Thanks
    Andrea

    Thanks for your reply,
    i think i'll go for another pair of PSN for the mobiles
    Andrea

  • How to add a new Local Variable for DataBase Logging?

    Hello
    I need to add a Local sequence variable to my STEP_RESULT table, i know i need to modify the schema by adding a new column but not sure on what to write in "Expression" to access the value of local variable. 
    Please reply asap, as its a little urgent.
    Regards
    Nitin Goel

    Hi
    you can read this here:
    http://digital.ni.com/public.nsf/allkb/F5ADBC61222343B586256CE00055E6D6?OpenDocument
    Regards
    DianaS

  • Can I use onboard variables for load program delay?

    I try to use the onboard function "load program delay" together with onboard variables. The program works and I could confirm with "read variable.flx" that the value has changed.
    Versions: lv6x, flexmotion 5x

    I am not sure I understand what the problem is. An onboard probgram using variables should work without any issues if you set a delay within it using the load program delay function.

  • Attempting to Save data from an access database file into a local variable for use.

    Hello! i'm trying to develop a small text based game in Visual Basic 2013 and I've recently decided i need to use a more sophisticated data storage system then dozens of .txt files and stream-readers. i'm using Microsoft access and i completed my database
    last night. it stores the stat and skill values of the player-character and the non-player characters. the problem is i cannot bring the data into visual basic in a usable way. using ado.net i can bring a single record into the system as a detail view and
    then read the data in from the labels but i'd far prefer to have it done purely through code. the book i purchased only covers data grid views and detail view and I've spent several hours searching for a solution online. 
    for clarification. i need to read each value in a record into a variable so i can calculate the stats for the games combat system.

    So, you want to select from MS Access?
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind_2012.mdb"
    Dim selectCommand As String
    Dim connection As New OleDbConnection(connectionString)
    selectCommand = "Select * From MyExcelTable ORDER BY ID"
    Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
    With DataGridView1
    .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    End With
    Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
    Dim table As New DataTable()
    table.Locale = System.Globalization.CultureInfo.InvariantCulture
    Me.dataAdapter.Fill(table)
    Me.bindingSource1.DataSource = table
    Dim data As New DataSet()
    data.Locale = System.Globalization.CultureInfo.InvariantCulture
    DataGridView1.DataSource = Me.bindingSource1
    Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
    Me.DataGridView1.AutoResizeColumns( _
    DataGridViewAutoSizeColumnsMode.AllCells)
    End Sub
    Then from DataGridView to a text file, right.
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim dt As DataTable = New DataTable
    Dim DBAdapter As OleDbDataAdapter = New OleDbDataAdapter
    Dim connection As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Excel\\Desktop\\Coding\\Microsoft Access\\Nor"& _
    "thwind.mdb;Jet OLEDB:System Database=system.mdw")
    Dim query As String = "SELECT * FROM Orders;"
    connection.Open
    Dim command As OleDbCommand = New OleDbCommand(query, connection)
    Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(command)
    adapter.Fill(dt)
    Dim writer As StreamWriter = New StreamWriter("C:\\Users\\Excel\\Desktop\\FromAccess.txt")
    For Each Row As DataRow In dt.Rows
    For Each values As Object In Row.ItemArray
    writer.Write(values)
    Next
    Next
    writer.Close
    End Sub
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

  • How can I use the same Sound variable for multiple sounds?

    I need my program to play many different mp3 files at different times.  I'm reading that you can not load different mp3 files into the same Sound variable.  But there must be a way around this right?  Can I Unload mp3 files some how?  Or can I delete the Sound variable and declare it again?  I don't want to have hundreds of Sound variables so what do I do?  Thank you.

    delete doesn't work in as3.  you must remove all listeners and references including nulling the variables.  for displayobjects, they need to be removed from the display list.
    p.s.  you don't need to create a sound instance until you need to load an mp3 using one.  so, if you're waiting for user input to start loading an mp3, you should wait for that input to create that sound instance.

  • How to use different (not local) user for NTLM auth in Authenticator?

    Hi All,
    I use custom authenticator to provide user / passwords to connect to .NET Web Services. I overloaded function getPasswordAuthentication() that returns right user / password combination for the requested URL. It all works perfectly for many kinds of HTTP connections: basic, ntlm, ntlm-v2, through proxy, ssl, etc.
    My problem is that during NTLM authentication from Windows computers JVM uses credentials of the currently logged in domain user instead of calling Authenticator to get other user / password provided by the user. In case when local user credentials fail to authenticate, JVM calls my Authenticator but in case authentication is successful it does uses local domain user and never calls my Authenticator. The issue is when this local domain user does not have enough permissions but authenticated correctly there is no way to supply JVM with another user to begin with.
    What can I do to force JVM to ignore local domain user and to use Authenticator to collect credentials during NTLM authentication requested by the server in case the software runs on a Windows box with currently logged in domain user?
    I am looking for the answer for a long time already but found only questions and suggestions to switch server from NTLM authentication which is not an option for me. From the developer's view it has to be pretty simple change for Sun to do in Java networking API. Is there any way to escalate it to Sun support? Maybe there is some property in some JRE patch level that allows to do this?
    Thank you very much!
    Mark

    Thank you for the reply. I have kind of an opposite problem. I can perfectly connect from Linux computers to Microsoft IIS servers using NTLM or even NTLMv2 authentication. My problem is connecting from Windows client computer joined to the same domain as IIS server with the domain user logged in to this computer. In this case this user account will be used in any HTTP connections I initiate to this IIS server instead of the one that I want to supply in my custom Authenticator.
    I have graphical interactive application that connects to IIS Server. When user runs it and connects to IIS server I want to prompt for the user/password regardless whether JRE may correctly authenticate using current user account credentials. The current user may not have enough permissions in IIS application so I want to use different user to login to IIS application.
    Thank you anyway,
    Mark

  • How to use Text and Image variables for printing

    I have been working on product configurator with AS3 for several months now.
    I am not proficient with AS3.
    Now, it seems that maybe my design is all wrong.
    Is there a proper way to do this?
    I have a main timeline that has movie clips showing images of different options for the product.
    On the first frame, I use buttons to select the choice for option 1 from the Option1_mc.
    Then I store the choice in a variable.
    I use a button to go to the next choice (frame 10.)
    On frame 10, I use buttons to select the choice for option 2 from the Option2_mc.
    This is stored in another variable.
    There are about 10 options that are selected and stored in variables.
    Some are text values and others are instances of images from the Option movie clips.
    I made a Print_mc to use for printjob.
    I can't get the values of the variables to display in the first frame for printing.
    Any helpl would be appreciated.

    you're welcome.
    you won't insert a variable into a textfield.  you'll assign the text property of your textfield to be the value one of your variables points to.
    so, for example, if you have:
    var var1:String="this is a test";
    you can use:
    tf.text=var1;

  • Using System::StartTime in variable for external file name comes out incorrect sometimes

    Hi All,
    I have an interesting dilemma.  I'm using SQL Server 2005 with Visual Studios 2005 (9.00.4035.00).
    I'm writing records from my database table out to an external flat file, nothing fancy other than in the naming of the file being dynamic and using system time.  So I have a couple of variables set:
    CR_Dir = \\host\directory\
    CR_Outfile = "AP_" +  (DT_WSTR, 4)  YEAR( @[System::StartTime] ) + RIGHT("0" + (DT_WSTR, 2) MONTH(@[System::StartTime] ),2) + RIGHT("0" + (DT_WSTR,2) DAY( @[System::StartTime] ),2) + RIGHT("0"
    + (DT_WSTR,2) DATEPART("Hh", @[System::StartTime] ), 2) + RIGHT("0" + (DT_WSTR,2) DATEPART("mi", @[System::StartTime] ),2) + RIGHT("0" + (DT_WSTR,2) DATEPART("ss", @[System::StartTime] ),2)
    + "_chref"
    And then in my Connection Manager properties I have an expression that brings them all together with a file extension:
    @[User::CR_Dir] +  @[User::CR_Outfile] + ".ctl"
    So what I should get for example is something like AP_20140309214502_chref.ctl  (if the job was run on 03/09/2014 @ 9:45pm) When executed properly.  I do this for two flat files one with an extension of .txt and the other with .ctl. 
    These steps are working fine the majority of the time.
    However, my problem is that occasionally, the portion of the filename that contains the datetime stamp is completely incorrect for one of the two files that are created during the same time frame.  And I'm not talking about a few seconds or even a minute
    or two, the date is off by weeks.  Here's an example:
    AP_20140309214502_chref.txt
    AP_20140213152253_chref.ctl
    This has happened twice since starting to run this job over the past four months, once on 12/15/2013 and again 03/09/2014.  This job is run every night at 9:45pm, and all the other days that this job runs the two filenames come out perfectly. 
    So I'm leaning towards something in the system that may be corrupting my variable every once in a while?  But because it happens intermittently how can I verify this?  Or is there a better way to perform what I'm trying to do that would be more accurate
    and consistent?
    Any help would be appreciated.
    Thanks
    Sawyer

    Hi All,
    I haven't found a solution to this issue.  I'm not actually able to reproduce it at will, so it's hard to troubleshoot.  What I've decided to do is rewrite my variable expression and make one system call for date and time and place it into
    a variable and then use the variable to build the file name.  Also I changed from using the System::Startime to using the GFETDATE() function (Don't know if this helps but it was easier to use in my substring when I parsed out the different time elements:
    v_DATETIME   STRING   SUBSTRING((DT_STR,30, 1252)GETDATE(), 1, 19)
    CR_Outfile      STRING   "AP_" + SUBSTRING(@[User::v_DateTime],1 ,4 ) + SUBSTRING(@[User::v_DateTime],6 ,2) + SUBSTRING(@[User::v_DateTime],9 ,2) + SUBSTRING(@[User::v_DateTime],12, 2) + (@[User::v_DateTime],15 ,2) + SUBSTRING(@[User::v_DateTime],18,2)
    + "_chref"
    I don't want to leave this thread as unanswered for too long so I'll give it another day or two and then close it.  I'll report back in a few months to let you all know if this problem has reoccurred or not.
    Thanks for the assistance.
    Sawyer

  • Using TCP or shared variable for data transfer

    I am trying to send a large amount of numbers from a real-time module to a host computer.  These numbers have been arranged into a large array, such as an array with 10s of thousands of points.  The time critical portion of getting the information has already been done, so the data transfer back to the host VI is not time critical.  I know I will need to break the large array down into smaller arrays and then reform the large array after all the information has been sent.  I know how to use both TCP and shared variables with FIFO.  What I am unsure of is which one is better to use for this application.  I do not know what the maximum size arrays I can send through either.
    Also, from what I have gathered from using LabView is that the sender has to be listening for a connection before the client opens a connection, or else it will throw an error.  When I tried breaking it down into 50 points, if i did not wait long enough in the host VI or if I did not put a long enough wait function in the RT loop, and error would throw, so it would take a long time to transfer the data when it worked properly.
    Any help or suggestions is appreciated, thanks.

    Regarding the array size question, there is no real limit (other then the amount of memory in your system) to the size of data that you can transfer in a single block using either TCP or the Shared Variable. In your case you can easily transfer an array with 10's of thousands of data points in a single write operation. Both TCP and the Shared Variable will automatically handle breaking up the data for the maximum packet size on Ethernet and then reconstitute the array on the receiving end. In LabVIEW you will simply get back the array as a whole without needing to worrying about how the data is broken into smaller packets on the Ethernet.
    I tested the attached example which transfers 400kB per block (50000 Doubles) without any problems. You do need to have the Server (in this case RT) running first before the client (Windows) can connect.
    Message Edited by Christian L on 02-09-2007 11:34 AM
    Christian Loew, CLA
    Principal Systems Engineer, National Instruments
    Please tip your answer providers with kudos.
    Any attached Code is provided As Is. It has not been tested or validated as a product, for use in a deployed application or system,
    or for use in hazardous environments. You assume all risks for use of the Code and use of the Code is subject
    to the Sample Code License Terms which can be found at: http://ni.com/samplecodelicense
    Attachments:
    TCP.JPG ‏44 KB

  • Help setting Parameters using JDBC and Bind Variables for Oracle List

    I fully understand the concept of using Bind Variables when using JDBC to avoid hard parses everytime my SQL statement is executed when only a certain value changes. For example, perhaps I have the following statement:
    PreparedStatement ps = con.prepareStatement("select salary from employees where employee_id = ?");
    I would then set the value of the question mark (the first and in this case only parameter) using:
    ps.getStmt().setString(1,empId1);
    That is assuming I have the variable empId1 populated with what I want. Anyway, my question has to do with Oracle lists. In other words, if I am just executing the statement against the db, it might look like:
    select salary from employees where employee_id in ('123','456','789');
    I still want to use bind variables and I can do it in JDBC with something like:
    select salary from employees where employee_id in ('123','456','789');
    ps.getStmt().setString(1,empId1);
    ps.getStmt().setString(2,empId2);
    ps.getStmt().setString(3,empId3);
    BUT, what if I just want to construct my list of ids upfront as a string and do something like:
    select salary from employees where employee_id in (?)
    ps.getStmt().setString(1,listOfEmpIds);where listOfEmpIds would look something like '123','456','789'.
    That's what I want to do but it doesn't work. It would be treating the list as a single parameter as opposed to lots of individual parameters. Can someone please tell me the syntax for this if it is possible? I have tried where XX in (?) and where XX in ? (and the string I substitute has the parenthesis in it), but neither work.
    Thank you for your help.

    I always build the list myself.
    You could, however, pass the list as a varchar to a stored proc and then have the stored proc parse (or dynamically execute) using it.
    The second method might even be faster although I would suspect that is only going to be the case if the list is very large. Or it might not.

Maybe you are looking for