Database query from jsp

hi! All
i am making the following query to the MySQL database from a jsp page but I get error. please help.
i am asking user to type in first few letters of person's first name and i use that string to find the match.
String getName = request.getParameter("search_name"); // gets the few letters entered by user
// fname is a field in the Employee table
rs = statement.excuteQuery("Select fname, lname, from Employee where fname.indexOf('" + getName + "') != -1");
Thanks in advance

It looks like you have Java code in your select statement.
I don't know what database your using but you want something
like this.
<%
String getName = request.getParameter("search_name");
/* I use ingress for my rdms and in ingress you use the keywork 'like'
   to match against character data. The '%' character is the wild card. So, this
   query looks for fname's that have any number of characters followed
   by the value stored in the java string getName, followed by any
   number of characters. */
rs = statement.excuteQuery("Select fname, lname, from Employee where fname like '%" + getName + "%'");
%>-S-

Similar Messages

  • Database Access from JSP - Is it correct?

    From a JSP Page, we need to retreive data from the database. We have our own application specific API commands to retreive data from database. We have doubts in using this API commands.
    Approach 1:
    From the jsp, send the query details to a Java file (BO). From the java file (BO), call the database and retreive the data
    Approach 2:
    Use the API command directly from the jsp page to retreive details from the database.
    In both approaches, the same API command is going to be used. We just want to know is there any advantage in calling the database through the java file (BO) instead of directly from the jsp?
    Regards,
    R.Aravinth

    Thanks Ram. But we are not going to have any complex
    codes written for data retreival. We just epxect a
    single line of code which will call database and that
    API command will return us a storage variable which
    we will use for displaying purpose.
    ok take a look at this
    //code to display lot of other stuff
    <%
        try {
           //code to access db and get data;
        catch(SomeException e){
            //oh-oh you are already on the display logic and have output a lot of stuff
            //how do you handle this
    %>versus this
    //code in some handler or bean
       try{
               //code to get data
              //set an attribute to enable a redirect to jsp page
        catch(Exception e){
              //handle exception, log ?
              //set an attribute to enable a redirect to error page
    Anyways, i wanted to know will the performance of the
    page improve if we call the database from a separate
    java rather than directly from jsp?As evnafets said, the answer is no. It may even be faster :)
    cheers,
    ram.

  • Database query from Java

    I'm writing a Java program that needs to query a Microsoft Access database. I'm not sure how to do this. Someone said to use ODBC drivers but I don't know what these are. Any clarification/ideas would be appreciated.

    There are a few easy step to set up a connection to your database in your java program.
    1. establish an odbc data source in windows control panel (may be under Administrative tools).
    2. you need to import the java.sql package.
    3. you need a connection, so type the following into your database class:
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    connection = DriverManager.getConnection("jdbc:odbc:/*your data source name goes here*/");
    catch (ClassNotFoundException exception)
    System.err.println("Failed to load JDBC/ODBC driver");
    exception.printStackTrace();
    System.exit(1);
    catch (SQLException exception)
    System.err.println("Unable to connect");
    exception.printStackTrace();
    System.exit(1);
    }4. Find an SQL tutorial on the web.
    5. For each query/update etc create a Statement object using the following code:
    try
    Statement statement = connection.createStatement();
    /* now use the remainder of this try block to execute your query. Each database query returns a ResultSet object */
    ResultSet resultSet = statement.executeQuery("/*your query string goes here*/");
    /* the next() method in ResultSet returns true if there are any more records, like an iterator. Therefore, you know if there are any results or not*/
    if (resultSet.next())
    /* If your query was a 'SELECT * FROM ...etc' then you will get a whole row from the table(s) within the database. if you need to extract a number from that record and you know the column number, then use the following */
    int id = resultSet.getInt(1);
    /* where 1 corresponds to the first column in the table, and so on. Ifyou want to extract a String, the use the getString() method*/
    catch (SQLException exception)
    }That's basically the easiest way to go about it (I think). Best to consult a book for a more in-depth look. Try Java - How to Program, by Deitel and Deitel (available at www.deitel.com). I found this very useful.

  • Problem while querying from jsp

    I have a query like this ...
    Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')='09/19/2004';
    I want to execute the same query using java for which i say
    String QQQ="Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')='?/?/?'"
    PreparedStatement stmt = conn.prepareStatement(QQQ);
    stmt.setString(1,"09");
    stmt.setString(2,"27");
    stmt.setString(3,"2004");
    But I am not getting the results. Is there anything wrong with the Qusetion marks(?) in the query ?
    I get the results if i directly enter the value for the question mark.
    Please help.
    Thanks.

    You would either need to explicitly concatenate the bind variables, i.e.
    String QQQ="Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')=? || '/' || ? || '/' || ?"or you would need to have a single bind variable and pass the whole string
    String QQQ="Select name,description,start_date from Events where TO_CHAR(start_date,'MM/DD/YYYY')=?"
    stmt.setString(1, "09/27/2004" );Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Database Access from JSP

    I'm trying to access a SQL Server database through an ODBC connection on a JSP page and having difficulties. This is the code that I'm using:
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:odbc:ODBCConnection", "username", "password");
    Statement stmt = conn.createStatement();
    ResultSet results = stmt.executeQuery(
    "SELECT numUserID, txtUsername, txtPassword FROM tblUsers");
    while (results.next()) {
    int DBuserid = results.getInt("numUserID");
    String DBusername = results.getString("txtUsername");
    String DBpassword = results.getString("txtPassword");
    conn.close();
    } catch (Exception exc) {                              
    out.println ("Exception \"" + exc + "\" occured....<br>");
    exc.printStackTrace();
    I've got two servers I'm testing it on. One is the IBM WebSphere 3.5 on Windows NT 4 and the other one is the Oracle 9i Server (Apache) with java support on Windows 2000. The code works fine on the Oracle server, but does not work on the WebSphere. I am getting a "java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Client unable to establish connection" exception. The problem is that I need to run this thing on the WebSphere server.
    I guess this might have something to do with the Java server differences or OS differences, but I don't know what that could be. I'm sure there's something that I'm not doing right, I just need some help figuring out what that is. I'd appreciate any help anyone can provide. Thanks.

    ODBC connection is set up the same on both servers and works with Access. In fact, I have tried to put the same code that I'm trying to use in a regular text java file, it compiled and ran on that same server. I've got a feeling I have the Websphere server setup wrong, but I don't know exactly what and how to fix it.
    Thanks.

  • Run a SQL procedure with multi database querying from Excel

    I'm using SQL Server 2008 Enterprise. I created a procedure in one database. The procedure is composed of several queries to different databases and the final combined result set is being displayed.
    I try to execute it via Excel, so the results will appear automatically in Excel sheet, but I'm getting the error:
    "The query did not run, or the database table could not be opened. Check the database server or contact your DBA. Make sure the external
    database is available and hasn't been moved or recognized, then try the operation again".
    I created a simpler procedure that queries only one database, and the results displayed at the Excel sheet with no issues.
    I suspect that, the original procedure failed due to the fact that I'm querying several databases in the procedure, when in the connection details of the "External Data Properties", only one database is mentioned.
    My question is - can it be solved? Can I use multiple databases in the procedure and see it in the Excel?
    Thanks, Roni

    Use Global Temporary table(##) instead of Local Temporary table(#).
    The scope of the temp table is limited to one database and it dispose automatically when jump to another database.
    No, that is not correct. From where did you get that idea?
    USE tempdb
    go
    CREATE TABLE #a(a int NOT NULL)
    INSERT #a(a) VALUES(9)
    go
    USE master
    go
    SELECT a FROM #a
    go
    USE msdb
    go
    SELECT a FROM #a
    go
    DROP TABLE #a
    And Roni's stored procedure does not even change database.
    ...however, the temp tables may very well be the problem, but for a completely different reason. Excel may ask SQL Server for the shape of the result set before it runs the procedeure, and this does not work with the temp tables. For this reason, using a
    table variable my save the show.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Insert data into table from JSP page using Entity Beans(EJB 3.0)

    I want to insert data into a database table from JSP page using Entity Beans(EJB 3.0).
    1. I have a table 'FRIENDS', (in Oracle 10g database).
    2. It has two columns, 'NAME' and 'CITY'. Both have datatype strings(varchar2).
    3. Now from a JSP page, having two textfields, 'NAME' and 'CITY', I want to insert data into table 'FRIENDS'.
    4. In between JSP and database is a Entity Bean(EJB 3.0) and a stateless session bean.
    5. I am using JDev as editor.
    Please provide me code ASAP or link with similar example.
    Thank you.
    Anurag

    Hi,
    I am also trying that scenario. So u can
    Post the jsp form data to a Servlet which will act as a Controller.
    In the servlet invoke the business method.
    Similar kind of app is in www.roseindia.net
    Hope this would help u.
    Meanwhile if u get any optimal solution, pls post it.
    Thanks,
    Happy Java Coding.

  • How to extract the Physical Query(database Query)

    Hi ,
    How to extract the Physical Query(database Query) from obiee which was fired in obiee
    Regards
    Ranga

    Hi Ranganath,
    Have a look the following links.
    Setting Logging level:
    http://gerardnico.com/wiki/dat/obiee/loglevel
    How to see physical query:
    http://gerardnico.com/wiki/dat/obiee/manage_session_log
    If you are new to OBIEE, spend some hours on the following blog to learn from basics to advanced level.
    http://gerardnico.com/wiki/
    http://obiee101.blogspot.com/
    http://www.rittmanmead.com/blog/
    Hope it helps you.
    Regards,
    Kalyan Chukkapalli
    http://123obi.com

  • Opening and closing database from JSPs

    Hi,
    I have a few web pages with an underlying database, and after some research I seem to have found that accessing this database directly from the JSP is a bad idea. Because of this I have created 2 methods in my JavaBean class to create the database connection and to close the database connection. What I want to have happen is when the user logs in the the site, a database connection is opened by calling the databaseConnection method then once they close the browser the destroyDBConnection is called. How do I go about implementing this approach in my JSPs? thanks for any suggestions
        * Method to create database connection
        public static void dbConnection() {
          try{
              // Step 1: Load the JDBC driver.
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                // Step 2: Establish the connection to the database.
                String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};" +
                        "DBQ=C:\\Program Files\\Apache Software Foundation\\Tomcat 5.5" +
                        "\\webapps\\TheatreDepartment.mdb";
                connection = DriverManager.getConnection(url);
              connection.setAutoCommit(false);
          } catch (SQLException se) {
              System.out.println("SQL Error while connecting to the database : "+
                                  se.toString());
          } /*catch (NamingException ne) {
              System.out.println("Naming exception Error while connecting to the database : "+
                                  ne.toString());
          } */catch (Exception ne) {
              System.out.println("Error while connecting to the database : "+
                                  ne.toString());
        * Destroy the Connection Object.
        public static void destroyDbConnection() throws SQLException {
              if (connection != null || !connection.isClosed() ) {
                connection.close(); // close the connection
      }

    I would suggest you do some more research.
    Take a look into connection pooling.
    Most of the time you do NOT want to give each individual user their own database connection, but rather keep a bunch on hand for people to use.
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-resources-howto.html
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html

  • Generate an xml file from Database query results

    Hi, can anyone help me out with this problem I'm having. What are the steps in creating an xml file directly from the results of a database query. I currently have a very simply process that queries a database via a partner link. The query returns the data but it's from this point that I am stuck. I need to create an xml file with the data along with the xml tags. I've looked at dozens of tutorials with no luck.
    I would greatly appreciate help with this.
    bpel rookie

    Should be quite simple.
    Create another partnerlink, configure it to use the file adapter, and write to an XML file. In this case you need to create an XML Schema (.xsd) of the file you want to create.
    Before you write to the file, either add assign steps to copy individual attributes or use a transform activity to convert from the database format to the file (xml) format.

  • How to generate XML file from oracle database query result

    Hi dudes,
    as stated on the subject, can anyone suggests me how can i achieve the task stated above??
    Here is a brief description of my problem:
    I need to create a XML file once i query from the oracle database, and the query result returned from the database will be stored in XML file.
    I'd searched around the JAXB, DOM, SAXP and the like basic concepts, but i still don't know how to start??
    Any suggestions ???

    Read this:
    http://www.cafeconleche.org/books/xmljava/chapters/ch08s05.html
    You might have to read more of the book to understand that chapter.

  • PC session hangs when launch a query from Oracle 9i client to 10g database

    I have a pc with Oracle 9.2.0.1.0 client installed. The database server level is 10.1.0.5.
    When I launch a query from a client session the pc sesssion locks up and doesn't return any results. When I launch the same query from the database server , or from other pcs with Oracle client 10 installed , I get results almost immediately from the query.
    The pc in question is running Windows XP Service pack 2. Other queries run fine from the pc.
    Are there are any known issues with Oracle 9 clients querying an Oracle 10 database ?

    Thank you for your reply. No, I must admit I didn't think of looking at the wait events. I will look at this as soon as I get a chance.
    Thanks again for your suggestion.

  • Select query from 2 schema & database

    Hi,
    what privileges should i give to execute select query from 2 schema & database in oracle
    thanks

    Hi,
    not so clear, if you are looking for this
    -- for other schema access
    GRANT SELECT ON <scheman_name>.<table_name> TO <schema_name>;
    or create the synonym
    --for other database access you need to create db link                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to connect oracle database using DSN  from jsp

    hello, can any know how can i connect to[b] oracle database using DSN name from jsp .I am using oracle 9i and Tomcat 5
    Using odbc tool i have created the dsn name but ithe connection does not make .here is the code that i have tried
    Connection connection = null;
         try
              Class.forName("oracle.jdbc.driver.OracleDriver");
         catch(ClassNotFoundException Exception)
              out.println("error occoured during loading the driver ");
         try
              out.println("getting the connection");
              connection = DriverManager.getConnection("jdbc:oracle:deepak","scott","tiger");
              out.println("connection getted");
         catch(Exception exception1)
              out.println("error occoured ");
    pls help as soon as possible
    Sorry, for my english

    you are actually using JDBC so the DSN entry does not matter.
    2 things.
    Make sure that your oracle database driver is in your classpath on your tomcat server.
    I.E. copy the file classes12.jar into your common/lib folder of tomcat, or into your WEB-INF/lib folder of your application. and RESTART your server. classes12.jar can be found on the internet or more easily somewhere within your oracle installation. just search for it.
    Make sure your jdbc url is correct. I believe it goes like this.... fill in the blacks
    connection conn = DriverManager.getConnection("jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDB");Note how the username are passed in the first string there fore there is no need to pass additional parameters. This method may be depriciated, but if so, just take out the user and pass from the string and continue to pass them as 3 seperate strings.
    connection conn = DriverManager.getConnection("jdbc:oracle:thin:MyOracleHost:1521:MyDB","scott","tiger");That should get your connection. if not, post your errors.

  • Insert date time into oracle database from jsp

    pls tell me ,from jsp how can I insert datetime values into oracle database .I am using oracle 9i .here is codethat i have tried
    html--code
    <select name="date">
    <option selected>dd</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    </select>
    <select name="month">
    <option selected>dd</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    </select>
    <select name="year">
    <option selected>dd</option>
    <option>2004</option>
    <option>2005</option>
    <option>2006</option>
    <option>2007</option>
    </select>
    here the jsp code
    <% date= request.getParameter("date"); %>
    <% month= request.getParameter("month"); %>
    <% year= request.getParameter("year"); %>
    try
    { Class.forName("oracle.jdbc.driver.OracleDriver"); }
    catch (ClassNotFoundException exception)
    try
         Connection connection = null;
         out.println("connectiong the database");
    connection = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcsid","scott","tiger");
    out.println("connection getted");
         int rows = 0;
         String query_2 = "insert into mrdetails values(?)";
         String dob = date+month+year;
         prepstat = connection.prepareStatement(query_2);
         prepstat.setTimestamp(4,dob);
         rows = prepstat.executeUpdate();
         out.println("data updated");
    catch (Exception exception3)
    out.println("Exception raised"+exception3.toString());
    }

    To insert date values into a database, you should use java.sql.Date. If it also has a time component, then java.sql.TimeStamp.
    Your use of prepared statements is good.
    You just need to convert the parameters into a date.
    One way to do this is using java.text.SimpleDateFormat.
    int rows = 0;
    String query_2 = "insert into mrdetails values(?)";
    String dob = date+"/" + month+ "/" + year;
    SimpleDateFormat sdf = new SImpleDateFormat("dd/MM/yyyy");
    java.util.Date javaDate = sdf.parse(dob);
    java.sql.Date sqlDate = new java.sql.Date(javaDate .getTime);
    prepstat = connection.prepareStatement(query_2);
    prepstat.setTimestamp(4,sqlDate);
    rows = prepstat.executeUpdate();
    out.println("data updated");Cheers,
    evnafets

Maybe you are looking for

  • What do the Ram timings mean and does it matter which SATA port?

    hi is it a thread or could you guys add 1. i just bought 2x p55a- gd65 mobos. im sorry i do not build pc's all the time. i buy every few years and try to get up to date tech.. my problem is. each new tech i go up say kn8 to an9 ddr to ddr2 etc. some

  • Auto-assign LPNs when performing receipts in Oracle WMS

    I am wondering if there is a way to auto assign LPNs to a receipt. Example: I order 2700 widgets 900 widgets = 1 Pallet When the Order arrives; using the Mobile Devices; do I have to receive each pallet individually or can I perform one receipt and h

  • Powerbook heats up with external display?

    I just recently got a 19 inch LCD Viewsonic VX924. I'm running the the mini dvi to dvi out to the external monitor with my powerbook display closed. I've noticed that the powerbook runs at a higher temperature with this setup and the fans are on abou

  • Ipod Touch 3g - alarms are silent, so not very useful!

    I have a 3rd generation touch that works great for most things, only last night for the first time I tried setting an alarm (not an app - the built-in alarms on the Clock page). My problem is that I can't really hear it. If I crank the volume way way

  • Can you take sofeware written on one computer and use it on another.

    We have a problem with the apllication maybe or the gpib. The apllication was working on one computer, but we change out that computer now we can get the program to work. A error message is generated (-107---) and fail to set up the test equipment.