Best practice needed to use PraparedStatments

Dear Experts;
I am using plain JDBC to intract with database, it works fine but what I am doing is, creating Connection and PreparedStatement in every method (where I need db interaction) and closing connection, resultSet and preparedStatment instances.
What I required, I dont need to create/close connections myslef. Yes If I want to insert a row in db i can achieve this by ... (but below I am using Statment not preparedStatmenmt, what will be the case in preparedStatement?)
public static boolean insert (string query)
// creating Connection
// creating statment
// executing stament.executeQuery(query)
// if insert successful setting retuenValue = true
// closing connection and statment
public insetRecord (User user)
  if (insert ("insert into user valaues "+user.getUserId+","+user.getUserId+")"))
  else
}any practice that you are using with preparedStatment.
I want to make this inset method generic for every table (and I want to use preparedStatments) and similarly fetching methods too.
thanks in advance
- Tahir

I am using plain JDBC to intract with database, it
works fine but what I am doing is, creating
Connection and PreparedStatement in
every method (where I need db interaction) and
closing connection, resultSet and
preparedStatment instances.Refractor to utility classes and methods. Or consider 3rd party DAO/ORM stuff, like Hibernate. They will care about them then.
What I required, I dont need to create/close
connections myslef. Yes If I want to insert a row in
db i can achieve this by ... (but below I am using
Statment not preparedStatmenmt, what will be the case
in preparedStatement?)Not closing them is bad practice. Consider connection pooling and reuseable SQL query strings for PreparedStatement.
I want to make this inset method generic for
every table (and I want to use preparedStatments) and
similarly fetching methods too.One word again: Refractor.
If your application is getting bigger, then it is really worth to take a look for a solid ORM solution. Hibernate is great.

Similar Messages

  • Best practice for development using REST API - OData

    Hi All, I am new to REST. I am a developer who works mostly in server-side code using Visual Studio. Now that Microsoft is advocating to write code using REST API instead of server-side code or client side object model, I am trying to use REST API.
    I googled and most of the example shows to write a code and put it on Content Editor/Script Editor. How to organize code and deploy to the staging/production in this scenario? Is there any Best Practice or example around this?
    Regards,
    Khushi

    If you are writing code in aspx or cs it does not mean that you need to deploy it in the SharePoint server, it could be any other application running from your remote server. What I mean it you can use C# & Rest API to connect to SharePoint server.
    REST API in SharePoint 2013 provides the developers with a simple standardized method of retrieving information from SharePoint and it can be used from any technology that is capable of sending standard HTTP requests.
    Refer to the following blog that provide your more details about comparison of the major features of these programming choices/
    http://msdn.microsoft.com/en-us/library/jj164060.aspx#RESTODataA
    http://dlr2008.wordpress.com/2013/10/31/sharepoint-2013-rest-api-the-c-connection-part-1-using-system-net-http-httpclient/
    Hope this helps
    --Cheers

  • Best practice for the use of reserved words

    Hi,
    What is the best practice to observe for using reserved words as column names.
    For example if I insisted on using the word comment for a column name by doing the following:
    CREATE TABLE ...
    "COMMENT" VARCHAR2(4000),
    What impact down the track could I expect and what problems should I be aware of when doing something like this?
    Thank You
    Ben

    Hi, Ben,
    Benton wrote:
    Hi,
    What is the best practice to observe for using reserved words as column names.Sybrand is right (as usual): the best practice is not to use them
    For example if I insisted on using the word comment for a column name by doing the following:
    CREATE TABLE ...
    "COMMENT" VARCHAR2(4000),
    What impact down the track could I expect and what problems should I be aware of when doing something like this?Using reserved words as identifiers is asking for trouble. You can expect to get what you ask for.
    Whatever benefits you may get from naming the column COMMENT rather than, say, CMNT or EMP_COMMENT (if the table is called EMP) will be insignificant compared to the extra debugging you will certainly need.

  • Best Practice Needed: Global Application Properties...

    Hi All,
    When developing a web-based application that reads certain configurable parameters from .properties files, I usually put the appropriate code in a static block in the appropriate Java class, storing the property in a static final constant. For example, a DBConnection class might have a static block that reads the driver, username, and password from a properties file.
    My question is, what are some "best practice" techniques for accessing and storing such parameters for use in an application? Are all global properties initialized in one class? at the same time? only when first needed?

    over all, I would say that your approach is fine. Personally, I load properties through a single class, some thing like PropertyReader, and have the different classes initialize their static fields via a get method on that class, like getProperty("db.user"). I prefer to load them via a single class because I can place all of my IO trapping in one location, it is easier to implement new security measures and, if necessary, easier to support internationalization.
    I initialize all properties once, at startup, into a Wrapper Object, typically ResourceBundle or Properties (although Hashtable or any some thing else would be suitable). I believe that it is best to initialize all properties at the same time, at startup because the costs of storing properties that may not be used is going to be less then the cost of making multiple IO calls to load properties on a need-by-need basis. In other words, you are almost always going to take a bigger performance hit by loading properties only when a request for that key is received, rather then just loading them all at once.

  • Building a best practice web application using ColdFusion and Jave EE

    I've been tasked with rewriting a software using ColdFusion.  I cannot seem to find a lot of information on best practice development in ColdFusion.  I am an experience Java developer who has never used ColdFusion before.  I want to build this application using a synergy of ColdFusion and Java EE technologies.  Can someone recommend me a book that outlines how to developer in ColdFusion?  Ideally this book assumes the reader is an experienced developer with no exposure to ColdFusion.  Ideally the methods outlined in the book are still "best practice" methods.

    jaisheela wrote:
    Hello Friends,
    I am also in the same situation.
    I am a building a new web application using JSF and AJAX.
    Requirement is I need to use IBM version of DOJO and JSF but I need to develop the whole application using Eclipse 3.3,2 and Tomcat 5.5.
    With IBM version of DOJO and JSF, will Eclipse and Tomcat help to speed up the development or do you suggest me to go for Rational Application Developer and WebSphere Application Server.
    If I need to go with RAD and WAS, then I am new to RAD and WAS, is it easy to use RAD and WAS for this kind of application and implement web applicaiton fast.
    Any feedback will be great help.Those don't sound like requirements of the system to me. They sound more like someone wants to improve their CV/resume
    From what I've read recently, if it's just fast you want, look at Ruby on Rails

  • Best practices followed in using Single Sign-On

    Hi Everybody,
    Now here is the toughest situation I have been facing on my project where I have to decide on how to use single sign-on(SSO) or whether SSO is the right solution for my problem.
    Here goes the problem :
    I have been developing a dashboard for my client using APEX 3.0.0.00.20 on Oracle Database 10g Enterprise Edition Release 10.2.0.2.0.
    Now the client do not want to create new logins for the end users on this new APEX application.
    After going through several threads in the forum about SSO I thought SSO might get me there but the confusion is how exactly SSO works for a situation like this.
    As per my understanding SSO would act like an intermediary staging place which would take the existing logins and associate with the APEX logins(please correct me if I am wrong).
    Also when I requested my DBA to install the SSO SDK as per the link http://www.oracle.com/technology/products/database/application_express/howtos/sso_partner_app.html#INSTALL I got a reply saying SSO is deprecated and now it is mod_osso.
    I need your thoughts and opinion on what the best practices being followed in projects like these.
    Thanks in advance.
    Raj.

    Teku,
    * You install the SSO SDK into a schema in the Application Express database.
    * You register the APEX site as an Oracle AS SSO partner application using the facilities of the AS Login Server which produces some "keys".
    * You take those keys and plug them into a script that you run in the APEX SSO SDK schema.
    * You create an APEX application and set its authentication scheme to SSO using a wizard or the authentication scheme edit pages in the Application Builder. (From this point on, you can create or modify any number of applications in any workspace (in this APEX database) to use SSO just by using the authentication scheme wizards/edit pages in the Application Builder.)
    *You run the application and get redirected to the login server.
    *The login server authenticates you based on username/password in OID.
    *The login server then redirects back to the requested page in your application.
    Scott

  • Best Practice for CTS_Project use in a Non-ChARM ECC6.0 System

    We are on ECC6.0 and do not leverage Solution Manager to any extent.  Over the years we have performed multiple technical upgrades but in many ways we are running our ECC6.0 solution using the same tools and approaches as we did back in R/3 3.1. 
    The future vision for us is to utilize CHARM to manage our ITIL-centric change process but we have to walk before we can run and are not yet ready to make that leap.  Currently we are just beginning to leverage CTS_Projects in ECC as a grouping tool for transports but are still heavily tied to Excel-based "implementation plans".  We would appreciate references or advice on best practices to follow with respect to the creation and use of the CTS_Projects in ECC.
    Some specific questions: 
    #1 Is there merit in creating new CTS Projects for support activities each year?  For example, we classify our support system changes as "Normal", "Emergency", and "Standard".  These correspond to changes deployed on a periodic schedule, priority one changes deployed as soon as they are ready, and changes that are deemed to be "pre-approved" as they are low risk. Is there a benefit to create a new CTS_Project each year e.g. "2012 Emergencies", "2013 Emergencies" etc. or should we just create a CTS_Project "Emergencies" which stays open forever and then use the export time stamp as a selection criteria when we want to see what was moved in which year?
    #2 We experienced significant system performance issues on export when we left the project intersections check on.  There are many OSS notes about performance of this tool but in the end we opted to turn off this check.  Does anyone use this functionality?  Any reocmmendations?
    Any other advice would be greatly appreciated.

    Hi,
    I created a project (JDeveloper) with local xsd-files and tried to delete and recreate them in the structure pane with references to a version on the application server. After reopening the project I deployed it successfully to the bpel server. The process is working fine, but in the structure pane there is no information about any of the xsds anymore and the payload in the variables there is an exception (problem building schema).
    How does bpel know where to look for the xsd-files and how does the mapping still work?
    This cannot be the way to do it correctly. Do I have a chance to rework an existing project or do I have to rebuild it from scratch in order to have all the references right?
    Thanks for any clue.
    Bette

  • Best practice for ConcurrentHashMap use?

    Hi All, would the following be considered "best practice", or is there a better way of doing the same thing? The requirement is to have a single unique "Handler" object for each Key:
    public class HandlerManager {
        private Object lock = new Object();
        private Map<Key,Handler> map = new ConcurrentHashMap<Key,Handler>();
        public Handler getHandler(Key key) {
            Handler handler = map.get(key);
            if (handler == null) {
                synchronized(lock) {
                    handler = map.get(key);
                    if (handler == null) {
                        handler = new Handler();
                        map.put(key, handler);
            return handler;
    }Clearly this is the old "double-checked-locking" pattern which didn't work until 1.5 and now only works with volatiles. I believe I will get away with it because I'm using a ConcurrentHashMap.
    Any opinions? is there a better pattern?
    Thanks,
    Huw

    My personal choice would be to use the reliable "single-checked-locking" pattern:
        public Handler getHandler(Key key) {
            synchronized(lock) {
                Handler handler = map.get(key);
                if (handler == null) {
                    handler = new Handler();
                    map.put(key, handler);
                return handler;
        }But I'm afraid the Politically Correct way of doing it nowadays looks as ugly as this:
    class HandlerManager {
        private Map<Key,Handler> map = new HashMap<Key,Handler>();
        private final Lock readLock;
        private final Lock writeLock;
        public HandlerManager() {
            ReadWriteLock lock = new ReentrantReadWriteLock();
            readLock = lock.readLock();
            writeLock = lock.writeLock();
        public Handler getHandler(Key key) {
            Handler handler = null;
            readLock.lock();
            try {
                handler = map.get(key);
            } finally {
                readLock.unlock();
            if (handler == null) {
                writeLock.lock();
                try {
                    handler = map.get(key);
                    if (handler == null) {
                        handler = new Handler();
                        map.put(key, handler);
                finally {
                    writeLock.unlock();
            return handler;
    }

  • Best practice: Retrieving data using DI server

    Hello experts,
    We are going to build a web shop using DI server. We are not going to use B1WS, because it is not supported and it seems like a lot of people can't get it to work (and so can't we).
    DI Server supports some Data Retrieve Messages, but most of them have a very restricted use. GetItemList for example only returns the item codes and item names. I can't limit the amount of returned values and I can't add columns to the results (if I'm mistaken about this, please tell me so!)
    What are best practices for this?
    Do I use the ExecuteSQL Data Retrieve Message in those cases (like 90-95% of the time) or do I use combinations of Data Retrieve Messages?
    Thanks for your time!
    Vincent

    Hi Vincent,
    What you mentioned are actual problems with current DI API and DI Server. You can't set the amount when using GetItemList both in DI API and DI Server.  The design maybe just consider the common requirements in mid/small size companies. So I think it's better to use ExecuteSQL if you have special requirement.
    Regards,
    MIN Hongjun

  • Best Practice / Solutions for using 11g DB+x86 or Small Computer to build iaas/paas?

    My customer wants to build their own iaas/paas using Oracle 11g DB, plus x86 or other small computer, running Linux or Solaris or Unix OS.
    Oracle Exadata is not feasible for them to use currently.
    Customer wants to know whether there are other customers have implemented their cloud solution based on these or not?
    If yes, would like to share the experience, presentation slides, best practices etc.
    Is there an Oracle email DL for asking this kind of question?
    Thanks,
    Boris

    Like Rick, I'm not aware of a specific "cloud implementors forum". Internally, Oracle has lots of material on implementing cloud, using any platform at all, although obviously we feel Engineered Systems are the most cost-effective solution for many customers. Are you interested in IaaS i.e. virtualised hardware, or PaaS i.e. DBaaS? They should not be confused, neither is required for the other, in fact, using IaaS to implement "DBaaS", as the OpenStack trove API attempts to do, is probably the most counter-productive way to go about it. Define the business-visible services you will be offering, and then design the most efficient means of supporting them. That way you gain from economies of scale, and set up appropriate management systems that address issues like patching, security, database virtualisation and so on.

  • Oil and gas best practices - need information

    Colleagues!
    Help me to find some information about sap oil and gas best bractices.
    I am interested in .ppt presentation, word documents that in some way describe best practices for oil and gas industry.
    Thanks in advance for your help.

    Hi,
    Can you please check this link http://www.sap.com/industries/oil-gas/index.epx.
    Hope this helps you.
    Rgds
    Manish

  • Best Practices needed -- question regarding global support success stories

    My customer has a series of Go Lives scheduled throughout the year and is now concerned about an October EAI (Europe, Asia, International) go live.  They wish to discuss the benefits of separating a European go Live from an Asia/International go live in terms of support capabilities and best practices.  The European business is definitely larger and more important than the Asia/International business and the split would allow more targeted focus on Europe.  My customer does not have a large number of resources to spare and is starting to think that supporting the combined go live may be too much (i.e., too much risk to the businesses) to handle.
    The question for SAP is regarding success stories and best practices.
    From a global perspective, do we recommend this split?  Do most of our global customers split a go live in Europe from a go live in Asia/International (which is Australia, etc.).  Can I reference any of these customers?  If the EAI go live is not split, what is absolutely necessary for success, etc, etc?  For example, if a core team member plus local support is required in each location, then this may not be possible with the resources they have u2026u2026..
    I would appreciate any insights/best practices/success stories/or u201Cwaru201D stories you might be aware of.
    Thank you in advance and best regards,
    Barbara

    Hi, this is purely based on customer requirement.
    I  have a friend in an Organization which went live in 38 centers at the same time.
    With the latest technologies in networking, distances does not make any difference.
    The Organization where I currently work in, has global business locations. In my current organization the go live was in phases. Here they went live in the region where the business was maximum first because this region was their largest and most important as far as revenue was concerned. Then after stabilizing this region, a group of consultants went to the rest of the regions for the go live in that region.
    Both the companies referred above are successfully into SAP and are leading partners with SAP. Unfortunately I am not authorized to give you the names of the Organizations as a reference for you as you requested.
    But in your case if you have shortage of manpower, you can do it in phases by first going live in the European Market and then in phases you can go live in the other regions.
    Warm Regards

  • Best Practice? Edit using Word - Acrobat X Pro to Distribute?

    I create Real Estate contracts/paperwork and email them to clients.  The clients then view, print, sign, and fax them back to me.
    I'm trying to figure out how to setup my system so that I can modify all my document packages in Word Format then distribute them via email in PDF Reader Compatible format (so that users can save and print but not modify) WITHOUT having to recreate the PDF forms or stamps i use each time I create the PDF.
    Considerations:
    I use the "Sign Here" and other stamps on the documents that are only visible before printing so that they understand the paperwork better.
    I need to include Word and not just go all-acrobat because the documents frequently change and I don't want to have to recreate the forms from scratch in Acrobat when they do.
    I also need to keep word because I use "Mail Merge" from to populate much of the data from an excel spreadsheet for me.  The rest is user-input.
    Software I have:
    Acrobat X Pro.
    MS Word 2010 Ultimate
    I'm not familiar with Acrobat enough to know which features are available to me to best carry out my job.  If anyone can point me in the right direction, to a tutorial perhaps, so that I might learn how to minimize my workload i'd really appreciate it!
    Thanks!
    Edit: PS. I need the final result to be a SINGLE PDF that I can attach to email.

    I've decided to try to simplify my question in hopes somebody can answer.
    How do most Realtors Prepare their paperwork for their Clients?
    Imagine this: a Real Estate Agent wants their client to fill-out a purchase contract and addendums.  They want their client's data to be auto-populated in the form before sending it.  The Realtor places stamps in the PDF so that their clients know where to initial or sign the document.
    Some clients need a buyers addendum with the contract, some need a dual-agency agreement with the contract, etc.
    Let's say there are three documents that could potentially be needed:
    Purchase Contract (Buyers and Sellers)
    Addendum (Buyers Only)
    Agreement (Sellers Only)
    It's the "package" that changes most of the time and not the data in the documents themselves.  I would like to be able to create a "Package" to send to the client based upon whether they're considered a "buyer" or a "seller". 
    Once the package is created, I need to be able to type data in certain fields and have them auto-populate throughout all other matching fields within each document (Price, for instance).  The forms wizard doesn't match up these fields so if the price field is in there 5 times, i have to type it in 5 different times.  To only do it once I have to manually change the tooltip/name to have them all change at the same time.
    Optimally, in each package I want to be able to import the client's information from Excel so that most of the person's information is auto-populated.  For example, their name & Address.
    My reality is that there aren't only 3 documents, there are 15-25 per client that I mix and match depending in their needs. THE CATCH is that sometimes I have to include protected forms to the package.
    If anyone can suggest the most efficient way to do this (or at least any way they do it), I'd really appreciate it.
    -Neil

  • Best practice of re-use a method in constructing a JFrame

    Hello All,
    I constructed a Main JFrame with the help of following method:
         JPanel createYpanel(JLabel lbl, JComponent txt){
              JPanel pane = new JPanel();
              pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
              pane.add(lbl);
              pane.add(txt);
              return pane;
         }Now, I need the above method for constructing a Child JFrame.
    What is the best programming approach?
    (a) Create a different private JPanel createYpanel(...) {...} in the Child JFrame, although it is 100% the same as that in the Main JFrame.
    (b) Make the method in the Main JFrame as static
    static JPanel createYpanel(...) {...}, so that it can be accessed by the Child JFrame as Main.createYpanel(lblA, cmpA);(c) Keep the method in the Main JFrame as non-static, but create an instance of the Main JFrame in the Child JFrame to access the method, such as
    JFrame mn = new Main();
    mn.createYpanel(lblA, cmpA);(d) None of the above. Please give me a better approach.
    My best guess:
    option (c) is the worst, since it needs to instantiate a Main JFrame only for the purpose of accessing this method and option (a) is redundancy although it can be done quickly by copy and paste. However, I'm not sure whether making a method static for this purpose is the best approach. Can anyone confirm this?
    Thank you for your help.
    Edited by: Patrick_Stiady on Jul 11, 2009 2:13 AM

    What is the best programming approach?I'm always reluctant to qualify any programming technique as "the best" - many ways to skin the cat.
    But here's my preference.
    (b) Make the method in the Main JFrame as staticYes.
    This instance method (currently) doesn't use any state nor collaborator from the instance, only its arguments.
    So it can be static. Indeed it should be static, for the other reasons you mention (no need to create an artificial "MainFrame" instance).
    However, you could locate this method in another class (+PanelUtility+, PanelFactory, whatever). Letting it in MainFrame, and using it from ChildFrame introduces a dependency that may not be relevant (if MainFrame publishes nothing else of use to the ChildFrame).

  • SqlCeConnection in CE 4.0: best practices for desktop use?

    I am using SQL Server CE 4.0 in a WinForms desktop application and was wondering what are the recommended practices for using SqlCeConnection in this context. I noticed some older threads on the topic however some of them talk mostly about mobile or are
    from a long time ago
    1. Should a new SqlCeConnection be created every time the DB is accessed or is it better to have on SqlCeConnection open and shared through the entire application?  My application can make frequent writes to the DB and when this happens I notice a noticeable
    UI lag if a new SqlCeConnection is created for which DB access.
    2. Can SqlCeConnection instances be shared across threads? On occasion my application performs DB reads in a background thread. Can I use the same SqlCeConnection instance from different threads?
    3. Are there any additional steps needed to ensure multi-thread safety when multiple threads can access the DB simultaneously when SQL Server CE is deployed in embedded mode? When I create a new SqlCeConnection for each DB access I ran into a few crashes
    and Monitor exceptions, possibly when multiple threads are accessing the same database.
    I am using SQL Server CE 4.0 embedded in a WinForms 2.0 Windows desktop application (non-mobile).  Any advice would be appreciated.

    You must use seperate SqlCeConnection etc object per thread, as these objects are not thread safe.
    I recommend opening the database on the main thread, and keep this connection unused and open for the lifetime of the app to keep the database file and engine "warm".
    Please mark as answer, if this was it. Visit my SQL Server Compact blog http://erikej.blogspot.com

Maybe you are looking for

  • Fixing Memory leaks in C code accessed via JNI

    Hi, I am working on an JNI interface between Java and legacy C code and I have problems with controlling the Memory inside the C code. In my application, I call many times from Java the C routines. In the C routines, memory is allocated but in a rath

  • Volume change sound Stopped Working! HELP!

    For some reason out of the blue...the sound i hear when I turn the volume up or down on my mac suddenly stopped playing I went to System Prefrences > Sound and tried everything but i cannot get that feature back..and i did not even disable it!

  • Itunes for leopard 10.5

    I have leopard 10.5.8. I tried to install the latest itunes. It wouldn't allow me to install the latest version. Reason: unknown error (11333)

  • Syncing apps, do I still have to pay?

    Hello, this is my first post. If I click 'Sync' in iTunes on my iPod's page, will it save what apps I have, onto iTunes and then if I delete them on my iPod, will I have to pay for them again? Thanks...

  • Status PAGE in q-notification

    hello everybody I just got a system status in a q-notification that says "PAGE". Anybody know what that status means and when it is set? Thanks a lot in advance Anja