Help! PreparedStatement

Hi, i'm currently working a JSP which gets an user input of a preparedStatement which looks like this:
"SELECT * FROM EMPLOYEE WHERE FirstName=? AND LastName=? AND City=?"
How can i get to another JSP page to ask the user to enter their values (For FirstName, LastName, City), so that it can replace the '?' in the preparedStatement??? And i can execute the preparedStatement...
Could someone pls help me out on this?? Coz i've tried out many times and i kept hitting errors...

You could try something like this. I did it this way
so I wouldn't have to mess with ps.setString. Just
keep in mind that this code is kind of messy, but it
should work.
PreparedStatement ps = null;
String tmp = "SELECT * FROM EMPLOYEE WHERE FirstName=?
AND LastName=? AND City=?";
int place = 0;
StringBuffer sb = new StringBuffer(tmp);
for(int i=0 ; ;i++) {
if((place = tmp.indexOf('?', place)) != -1)
e)) != -1) {
//Prompt user for ? value and get the
lue and get the value
// userValue is the value entered by
alue entered by user
sb.deleteCharAt(place);
sb.insert(place, "'" + userValue +
" + userValue + "'");
place++;
else {
break;
ps = con.prepareStatement(sb.toString());
It is pointless using a preparedstatment in this example, you may aswell just use a statment. 2 advantages of the preparedstatmet are:
i) The sql statment is precompiled onto the database server so the second and subsiquent time the preparedstatment is called performance is improved ( assuming the JDBC driver supports this ). If you replace the question marks before con.prepareStatement() the statment will be precompiled again and again rather than just once, that wouldnt be good for performance.
ii) When using ps.setString() ps.setInt() or whatever you dont have to worry about escape characters or adding ' characters to CHARACTER values but not to DECIMAL values, the implementation does this for you.
I dont know how you can that you are "messing with setString()" when the code above is the alternative.
Candy.. why dont you have a html form with a firstname / lastname and city field, read the values into Strings and call the use the preparedstatments setString(), what could be easier ;-)

Similar Messages

  • Prepared statement help... pls...

    hey all... need help... this prepared statement is driving me mad... keeps throwing an error in my servlet.... can somebody pls help
         PreparedStatement updateWiki = con.prepareStatement("UPDATE sportinfo SET pageinfo,parent = (?,?) WHERE sport LIKE ? ");
              updateWiki.setString(1, wikipage);
              updateWiki.setString(2, parent);
              updateWiki.setString(3, sport);
              updateWiki.executeUpdate();
    am i missing something???
    thanks keith

    1. What is the error? Please post it.
    2. Try using the query like:
    UPDATE sportinfo SET pageinfo=?,parent=? WHERE sport LIKE ?
    and see if it still fails.

  • JDBC security in JSP

    Hi,
    I would like to clear a String from possible hostile SQL-commands that might exist in the String. The reason is that I get login and pw from the user (with request.getParameter) and then use that text in order to search my database for matches. So how do I get rid of all SQL-commands in the string?
    It's a rather serious security-breach...

    True, you can never be too security concious where a webapp is concerned but PreparedStatement's help:
    PreparedStatement s = con.prepareStatement("SELECT gid FROM users WHERE id=? AND pw=?");
    s.setString(1,id);
    s.setString(2,pw);
    s.executeUpdate();
    And then a client passes:
    blub OR 1=1
    fuff OR 2=2
    will be executed as:
    SELECT gid FROM users WHERE id='blub OR 1=1' AND pw='fuff OR 2=2'
    ..as the setString() method also adds the single quotes.
    However what you point out may be a possibility (?) for setInt() method so I guess we should be careful when using 2 setInt()'s in the same call..
    HTH
    Mike.

  • Try to retrieve data from database got error message

    Try to retrieve data from database got error message *"java.lang.ArrayIndexOutOfBoundsException: 2*
    *     sun.jdbc.odbc.JdbcOdbcPreparedStatement.clearParameter(JdbcOdbcPreparedStatement.java:1023)*
    *     sun.jdbc.odbc.JdbcOdbcPreparedStatement.setDate(JdbcOdbcPreparedStatement.java:811)*
    *     guestbk.doGet(guestbk.java:32)*
    *     guestbk.doPost(guestbk.java:73)*
    *     javax.servlet.http.HttpServlet.service(HttpServlet.java:710)*
    *     javax.servlet.http.HttpServlet.service(HttpServlet.java:803)"*
    I have used prepared statment
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yy");
                java.util.Date dt = sdf.parse(str3);
                       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                       con=DriverManager.getConnection("jdbc:odbc:gbook");
                       //Statement stmt=con.createStatement();
    PreparedStatement ps = con.prepareStatement("SELECT * from gbook where emailid =? AND date =?");
    ps.setString(1,str1);
    ps.setString(2,str2);
    ps.setDate(3,new java.sql.Date(dt.getTime()));
    //ps.executeQuery();
                       //ResultSet rs=stmt.executeQuery("select * from gbook where emailid = str1");
                  ResultSet rs = ps.executeQuery();
                       out.println("<Html>");
                    out.println("<Head>");
                       out.println("<Title>GuestBook</Title>");
                       out.println("</Head>");
                       out.println("<Table border=1 align=center >");
                       out.println("<H4><B><center>Teacher's Lesson Plan</center></B></H4><BR>");
                       out.println("<TR><TD><b>Teacher Name</b></TD><TD><b>Class</b></TD></TR>");
               while(rs.next())
                        ctr++;
                        String email=rs.getString("emailid");
                        String cmt=rs.getString("comment");
                        out.println("<TR><TD>"+email+"</TD><TD>"+cmt+"</TD></TR>");
            }Please anybody help .

    PreparedStatement ps = con.prepareStatement("SELECT * from gbook where emailid =? AND date =?");
    ps.setString(1,str1);
    ps.setString(2,str2);
    ps.setDate(3,new java.sql.Date(dt.getTime()));Your SQL query has 2 placeholders but you try to set 3 values.
    And didn't you read the stack trace?
    guestbk.doGet(guestbk.java:32)You could've tracked down line 32 and seen what was there at that line.
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://www.catb.org/~esr/faqs/smart-questions.html
    ----------------------------------------------------------------

  • Help needed, Oracle and PreparedStatement setNull for VARCHAR problem

    Using the JDBC drivers included with JDK 1.3, I am encountering a strange problem when trying use a PreparedStatement with a NULL parameter in a VARCHAR column. When running the code below (user_id is an integer and login is a nullable varchar) the program will simply wait and wait and wait.
    import java.sql.*;
    public class OracleNullTest {
         public static void main(String [] args) {
              try {
              String odbcName = args[0];
              String dbUserName = args[1];
              String dbPassword = args[2];
              int id = Integer.parseInt(args[3]);
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              Connection con = DriverManager.getConnection("jdbc:odbc:"+odbcName, dbUserName, dbPassword);
              PreparedStatement ps = con.prepareStatement("Insert into junk(user_id, login) values(?,?)");
              ps.setInt(1,id);
              ps.setNull(2,Types.VARCHAR);
              ps.executeUpdate();
              ps.close();
              con.close();
              } catch (Exception e) { e.printStackTrace(); }
    If I change the 'ps.setNull(...)' to 'ps.setString(2,"test")' things work fine. Furthermore, I've changed the VARCHAR column to a TIMESTAMP and setting it to null works fine. The above code works fine on DB2 and SQL Server so only Oracle is anatagonizing me.
    Any insight or help is greatly appreciated.

    The ODBC driver has nothing to do with java. What you are using in java is a JDBC driver.
    Various microsoft products install a ODBC Oracle driver. Oracle also provides a driver that is installed with the Oracle Client install.
    I have seen reports that suggest the MS driver as good as the Oracle driver, consequently that could be source of your problem.

  • Help In PreparedStatement

    I need some help with SQL and PreparedStatement
    I have add the PreparedStatement and I'm not to sure if I'm doing it correctly.
    When I do a test run on Choose 1 ,2 or 3 I now I get this error.
    Error - com.mysql.jdbc.Statement
    here is my code below
    import java.sql.*;
    import java.util.*;
    import java.sql.PreparedStatement;
    public class DBAssign {
          * @param args
         static Scanner kbd;
         static Connection conn = null;
    //adding records...
         public static void addRecord(String id, String fname, String lname,
                   String street, String city, String state, String zip,
                   String hphone, String ophone, String deptasg, int yrsemp,
                   float mtpy) throws SQLException {
              // make variables
              PreparedStatement statement = null;
              String addstring = "Insert into emptable values('" + id + "', '"
                        + fname + "', " + lname + ", '" + street + "'" + city + "',"
                        + state + "'," + zip + "'," + hphone + "'," + ophone + "'"
                        + deptasg + "'," + yrsemp + "'," + mtpy + "',)";
              try {
                   statement=conn.prepareStatement("INSERT into user values(?,?)");
                   statement = (PreparedStatement) conn.createStatement();
                   boolean ret = statement.execute(addstring);
                   if (ret) {
                        System.out.println("Updated " + statement.getUpdateCount());
                   }//close if
              } catch (SQLException e) {
                   System.out.println("Error " + e.getMessage());
                   throw (e);
              } finally {
                   try {
                        if (statement != null) {
                             statement.close();
                        }//close if
                   } catch (SQLException e2) {
                        System.out
                                  .println("Error freeing resources " + e2.getMessage());
                        throw (e2);
                   }//close e2
              }//close finally
         }//close exception
    //add to the record
         public static void addToTable() {
              // get data from keyboard
              String id = null;
              String fname; // =null;
              String lname;
              String street;
              String city;
              String state;
              String zip;
              String hphone;
              String ophone;
              String deptasg;
              int yrsemp;
              float mtpy;
              boolean dupkey = true;
              while (dupkey == true) {
                   System.out.println("Enter Employee's ID");
                   id = kbd.next();
                   kbd.nextLine();
                   dupkey = findRecord(id);
                   if (dupkey == true) {
                        System.out.println("Key must be unique - try again");
              System.out.println("Enter first name");
              fname = kbd.next();
              kbd.nextLine();
              System.out.println("Enter last name");
              lname = kbd.next();
              kbd.nextLine();
              System.out.println("Enter street name");
              street = kbd.next();
              kbd.nextLine();
              System.out.println("Enter city");
              city = kbd.next();
              kbd.nextLine();
              System.out.println("Enter state");
              state = kbd.next();
              kbd.nextLine();
              System.out.println("Enter zip code");
              zip = kbd.next();
              kbd.nextLine();
              System.out.println("Enter home phone number");
              hphone = kbd.next();
              kbd.nextLine();
              System.out.println("Enter office phone");
              ophone = kbd.next();
              kbd.nextLine();
              System.out.println("Enter dept name");
              deptasg = kbd.next();
              kbd.nextLine();
              System.out.println("Enter years employeed");
              yrsemp = kbd.nextInt();
              kbd.nextLine();
              System.out.println("Enter month pay");
              mtpy = kbd.nextFloat();
              kbd.nextLine();
              try {
                   addRecord(id, fname, lname, street, city, state, zip, hphone,
                             ophone, deptasg, yrsemp, mtpy);
              } catch (SQLException e) {
                   System.out.println("Error adding record " + e.getMessage());
         }//close add
    //List records     
         public static void listRecords() {
              PreparedStatement statement = null;
              ResultSet rs = null;
              try {
                   statement = (PreparedStatement) conn.createStatement();
                   rs = statement
                             .executeQuery("Select empid, firstname, lastname, street, city, state, zip, homephone, officephone, department, yearsemploy, monthpay");
                   if (rs != null) {
                        while (rs.next()) {
                             System.out.println(rs.getString("empid") + " - "
                                       + rs.getString("firstname") + " - "
                                       + rs.getInt("lastname") + " - "
                                       + rs.getString("street") + " - "
                                       + rs.getString("city") + " - "
                                       + rs.getString("state") + " - "
                                       + rs.getString("zip") + " - "
                                       + rs.getString("hphone") + " - "
                                       + rs.getString("ophone") + " - "
                                       + rs.getString("department") + " - "
                                       + rs.getString("yearsemploy") + " - "
                                       + rs.getString("monthpay"));
                        }// close the while loop
                   }// close the if loop
              } catch (SQLException e) {
                   System.out.println("Error listing records: " + e.getMessage());
              } finally {
                   try {
                        if (statement != null) {
                             statement.close();
                        if (rs != null) {
                             rs.close();
                   } catch (SQLException e2) {
                        System.out.println("Error freeing resource" + e2.getMessage());
              }//close finally
         }//close list
    //Find a record
         public static boolean findRecord(String empid) {
              boolean retval = true;
              PreparedStatement statement =  null;
              ResultSet rs = null;
              int countemps = 0;
              try {
                   statement = (PreparedStatement) conn.createStatement();
                   rs = statement
                             .executeQuery("Select count(*) as num from emptable where empid = '"
                                       + empid + "'");
                   rs.next();
                   if (rs == null) {
                        retval = false;
                   } else {
                        countemps = rs.getInt(1);
                   // System.out.println("Count "+countrecs);
                   if (countemps <= 0) {
                        retval = false;
              } catch (SQLException e) {
                   System.out.println("Error finding Employees record "
                             + e.getMessage());
              } finally {
                   try {
                        if (statement != null) {
                             statement.close();
                        if (rs != null) {
                             rs.close();
                   } catch (SQLException e2) {
                        System.out.println("Error freeing resource " + e2.getMessage());
                        retval = true;
              }//close finally
              return retval;
         }//close find
    //updates records
         public static void updateRecord() {
              // get record to update
              String id = null;
              boolean findemp = false;
              while (!findemp) {
                   System.out.println("Enter Employee ID to update");
                   id = kbd.next();
                   kbd.nextLine();
                   findemp = findRecord(id);
                   if (!findemp) {
                        System.out.println("This Employee id record " + id
                                  + " does not exist - try again");
              }//close while
              // display data and request update
              Statement stmt = null;
              ResultSet rs = null;
              String id2 = null;
              String fname;
              String lname;
              String street;
              String city;
              String state;
              String zip;
              String hphone;
              String ophone;
              String deptasg;
              String yrsemp;
              String mtpy;
              try {
                   stmt = conn.createStatement();
                   rs = stmt.executeQuery("Select * from emptable where empid = '"
                             + id + "'");
                   rs.next();
                   System.out.println("Item First Name is "
                             + rs.getString("firstname"));
                   System.out.print("Enter new item name: ");
                   fname = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Last name is " + rs.getString("lastname"));
                   System.out.print("Enter new item name: ");
                   lname = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Street is " + rs.getString("street"));
                   System.out.print("Enter new item name: ");
                   street = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item City name is " + rs.getString("city"));
                   System.out.print("Enter new item name: ");
                   city = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item State name is " + rs.getString("state"));
                   System.out.print("Enter new item name: ");
                   state = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Zip Code is " + rs.getString("zip"));
                   System.out.print("Enter new item name: ");
                   zip = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Home Phone is " + rs.getString("homephone"));
                   System.out.print("Enter new item name: ");
                   hphone = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Office Phone is " + rs.getString("officephone"));
                   System.out.print("Enter new item name: ");
                   ophone = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Department is " + rs.getString("department"));
                   System.out.print("Enter new item name: ");
                   deptasg = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Years Employed is " + rs.getString("yearsemploy"));
                   System.out.print("Enter new item name: ");
                   yrsemp = kbd.next();
                   kbd.nextLine();
                   System.out.println("Item Monthly pay is " + rs.getString("monthpay"));
                   System.out.print("Enter new item name: ");
                   mtpy = kbd.next();
                   kbd.nextLine();
                   String updatestring = "Update emptable set FirstName = '" + fname
                             + "', Last name=" + lname + ", street='" + street
                             + "', City=" + city + ", State=" + state + ", Zip Code="
                             + zip + ", Home Phone=" + hphone + ", Office Phone="
                             + ophone + ", Department=" + deptasg + ",Monthly=" + mtpy
                             + " Years Employed=" + yrsemp + " where empid = '" + id2
                             + "'";
                   stmt.execute(updatestring);
                   int updatenum = stmt.getUpdateCount();
                   if (updatenum < 1) {
                        System.out.println("Error on update");
                   } else {
                        System.out.println("Updated " + updatenum + " records");
              } catch (SQLException e) {
                   System.out.println("Error - " + e.getMessage());
              } finally {
                   try {
                        if (stmt != null) {
                             stmt.close();
                        if (rs != null) {
                             rs.close();
                   } catch (SQLException e2) {
                        System.out.println("Error " + e2.getMessage());
              }//close finally
         }//close updates
    //deleted the record  (this section is working
         public static void deleteRecord() {
              Statement stmt = null;
              String delstring;
              String id;
              try {
                   stmt = conn.createStatement();
                   boolean findrec = false;
                   while (!findrec) {
                        System.out.println("Enter Employee ID to delete");
                        id = kbd.next();
                        kbd.nextLine();
                        findrec = findRecord(id);
                        if (!findrec) {
                             System.out.println("This Employee id record " + id
                                       + " does not exist - try again");
                        }//close if
                        // delete record
                        delstring = "Delete from emptable where empid = '" + id + "'";
                        stmt.execute(delstring);
                        System.out.println("Deleted " + stmt.getUpdateCount()
                                  + " records");
                   }//close while
              } catch (SQLException e) {
                   System.out.println("Error deleting record " + e.getMessage());
              } finally {
                   try {
                        if (stmt != null) {
                             stmt.close();
                   } catch (SQLException e2) {
                        System.out.println("Error removing employee info");
              }//close finally
         }//close public
         public static void showMenu() {
              System.out.println("---------------");
              System.out.println("1. List employees records");
              System.out.println("2. Add employees record");
              System.out.println("3. Update employees record");
              System.out.println("4. Delete employees record");
              System.out.println("5. Exit");
         public static int getOption() {
              int optn = 99;
              while (optn > 5 || optn < 1) {
                   System.out.println("---");
                   System.out.println("Enter option");
                   System.out.print("===>");
                   optn = kbd.nextInt();
              }//close while
              return optn;
         public static void main(String[] args) {
              int optn = 99;
              String host = "localhost";
              String database = "empdata";
              String user = "root";
              String pass = "";
              // make keyboard object
              kbd = new Scanner(System.in);
              String connstring = "jdbc:mysql://" + host + "/" + database + "?user="
                        + user + "&password=" + pass;
              try {
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
                   conn = DriverManager.getConnection(connstring);
                   while (optn != 5) {
                        showMenu();
                        optn = getOption();
                        switch (optn) {
                        case 1:
                             listRecords();
                             break;
                        case 2:
                             addToTable();
                             break;
                        case 3:
                             updateRecord();
                             break;
                        case 4:
                             deleteRecord();
                        case 5:
                             System.out.println("OK - later Come back soon");
                        default:
                             break;
                        }//close switch
                   }//close while
              } catch (ClassNotFoundException e1) {
                   System.out.println("ERROR - Class not found " + e1.getMessage());
              } catch (SQLException e2) {
                   System.out.println("ERROR - " + e2.getMessage());
                   System.out.println("ERROR - " + e2.getSQLState());
              } catch (Exception e3) {
                   System.out.println("Error - " + e3.getMessage());
         }//close main
    }//close classAny help would be great.
    Red

                   statement=conn.prepareStatement("INSERT into user values(?,?)");
                   statement = (PreparedStatement) conn.createStatement();
                   boolean ret = statement.execute(addstring);Why are you assigning statement twice?
    Example of a prepared statement as follows:
    String insertStr = "SELECT fname, lname FROM Person WHERE mName = ?";
    PreparedStatement pStmt = conn.prepareStatement (insertStr);
    pStmt.setString(index, middleName);
    pStmt.execute();

  • Need help with PreparedStatement...

    I have a Java aplication connected witn my hsqldb. So the Java aplication is a screen in wich the user can click on buttons and insert, delete, edit, search, data on the database.
    For example, I trying to use PreparedStatement for use with INSERT INTO TABLENAME ....
    But the problem is that the values that will be insert into the table of my database, these values will be entered by the user by a JOptionPane. In fact, a variable will take the value entered on the JOptionPane.
    How can I insert new Data to my Table with the PreparedStament + values entered by the user?
    Thanks for helping me.
    I just love Java!

    You need JavaDoc for java.sql.PreparedStatement here.
    Basically, PreparedStatement allows you to send values from variables.
    After that, you may use one of these methods to handle the tasks.
    executeQuery -> Select
    executeUpdate -> Insert/Update/Delete
    e.g.
    SQL is "DELETE FROM TBL WHERE abc = ?"
    // you know what you need to do here, right?
    preparedStatement.setString(1, "value");
    preparedStatement.executeUpdate();That's it.
    Good luck
    :D

  • PreparedStatement setDate Help

    hi.
    I wonder what wrong with my code:
    Date tDate = new Date();
    PreparedStatement preStmt;
    String str = "UPDATE READERTRACK SET LastVisit = ?, NumTimes = ? WHERE";
    str += " TYPE = ?";
    System.out.println(str);
    preStmt = conn.prepareStatement(str);
    preStmt.clearParameters();          
    preStmt.setDate(1, tDate);     
    preStmt.setInt(2, numTime+1);
    preStmt.setString(3,getCriteria());          
    preStmt.executeUpdate();
    preStmt.close();
    conn.close();
    it give an error saying:
    cannot resolve symbol
    symbol : method setDate (int,java.util.Date)
    location: interface java.sql.PreparedStatement
    help
    thanks. :D

    Sure thing. I found I was getting all kinds of exceptions with inserting dates into SQL Server. The worst was a fractional truncation exception that happened from time to time.
    My first attempt was to insert a timestamp object using setTimestamp() method which gave me above exception. Now I use Strings for all inserts of dates using the setObject() method and haven't had a problem since. e.g.
    String date = "01-MAR-1990"
    stmt.setObject(1, date);

  • Troubled with PreparedStatement, please help

    Hello all:
    Here is a seemingly too simple a problem which is already taking my day. Please help.
    String x=null;
    String querry1 = null;
    String querry2 = null;
    ResultSet rs = null;
    Statement st = null;
    PreparedStatement pstmt = null;
    try {
    st = conn.createStatement();
    //MAKE FIRST QUERRY
    querry1 = "SELECT * FROM table1 WHERE (a= ? OR b = ?)";
    pstmt = conn.prepareStatement(querry1);
    pstmt.setString(1, userInput);
    pstmt.setString(2, userInput);
    rs = pstmt.executeQuery();
    while(rs.next()){
    //Process the result set.
    //The value of x is one of the values in the result set.
    //Hence get it.
    x = rs.getString("C");
         }//end while
    //No problem up to here.
    //For check, output the value of x
    System.out.println(x); //correct non-null value is displayed
    //MAKE SECOND QUERRY based on the value of 'x'
    querry2 = "SELECT * FROM table2 WHERE C= ? ";
    //Table 1 and table 2 have a common column C.
    //I want to retrieve the value from table 2 for which C=x;
    pstmt = conn.prepareStatement(querry2);
    pstmt.setString(1, x);
    rs = pstmt.executeQuery();
    //The problem is that in this 2nd querry, SQL error is caught, with the message
    "java.sql.SQLException: Illegal operation on empty result set"
    //whereas it should have produced a valid value.
    //When the querry is formed explicitly (as follows), there is no problem. Result set is OK.
    //when the value of x is "mystring", then the follwoing 3 lines work
    pstmt = conn.prepareStatement(querry2);
    pstmt.setString(1, "mystring");
    rs = pstmt.executeQuery();
    Please teach me what the hell I'm not getting here.
    Thank you.

    I would have thought you'd get this exception:
    "java.sql.SQLException: Illegal operation on empty result set"
    because you're trying to call something like:
    rs.getString("foo");on an empty ResultSet. You can test whether the ResultSet has any rows as ResultSet.next() returns a boolean value, i.e.:
    if (rs.next())
        rs.getString("foo");
    }So the question is why is your second ResultSet empty? Maybe the value of C you are getting from table1 has leading/trailing whitespace that is not in table2?

  • PreparedStatement help

    //First insert
    PreparedStatement pstmtU = cnn.prepareStatement(sql);
         pstmtU.setInt(1, 78);
         pstmtU.setString(2, aa);
         pstmtU.setString(3, bb);
    pstmtU.executeUpdate();
    pstmtU.close();
    //Second insert
    PreparedStatement pstmtQ = cnn.prepareStatement(sql1);
         pstmtQ.executeString(1, zz_seq.currval);
         pstmtQ.executeString(2, xx);
         psQ.executeUpdate();
    pstmtQ.close();when I am writing and compiling just first statement then its ok but when am adding the second it gives error "Cannot resolve symbol"

    thanks g_magoss but now it gives just one error i.e.
    pstmtQ.setString(1, zz_seq.currval);Error: Cannot resolve symbol

  • Urgent help Statement v/s PreparedStatement

    iam using Statement object but java specification says, PreparedStatement makes more efficient compared to Statement object can any body explain briefly about it.

    i know that dynamically u can give values but specification says
    PreparedStatements make the description calls at construction time,
    Statements make them on every execution.what this means If you want to execute a sql statement multiple times, then a prepared statement is more efficient.
    eg
    Statement stmt = connection.createStatement();
    stmt.execute("insert into users (username) values ('Tom')");
    stmt.execute("insert into users (username) values ('Dick')");
    stmt.execute("insert into users (username) values ('Harry')");vs
    [code
    String sql = "]insert into users (username) values (?);";
    stmt = connection.prepareStatement(sql);
    stmt.setString(1, "Tom");
    stmt.execute();
    stmt.setString(1, "Dick");
    stmt.execute();
    stmt.setString(1, "Harry");
    stmt.execute();
    With the first one, the database has to parse the query each time, check it for syntax errors, and then execute it.
    Using a prepared statement, the parsing/error checking only happens once - when you prepare it. After that you can call the same statement with different values, and it will use that already "parsed and prepared" statement.
    It already knows exactly the column types that will be returned from the query - that bit can't change. With a Statement, it has to work from scratch each time.
    If you are executing the same piece of SQL hundreds/thousands of times, only changing the values, then Prepared statements come into their own.
    Cheers,
    evnafets

  • Help with PreparedStatement

    Hi Friends,
    I am trying to insert Hebrew string into my database from my Java based tool. I am using SQL Server 2005 and the latest MS SQL jdbc driver. After i insert the string, all the Hebrew characters are in an unreadable format (some junk basically).
    My requirement is to download the rows of that particular table of the database (containing Hebrew) into an EXCEL sheet, give the corresponding english translation and upload it back. But since i am getting junk characters in the excel sheet, i am unable to translate
    I tried defining the column name as nvarchar and now i am able to directly insert the Hebrew data into the database table. So now I am sure that the issue is NOT with sql server but with my PreparedStatement.
    insert into Static_String1 values (N'&#1506;&#1489;&#1512;&#1497; &#1514;')The above command works fine, as I
    am appending N with the Hebrew string when inserting. But the problem
    is in my real code, I wont be able to append N with the dynamic string
    variable :(
    Here is my code piece
    sql = "insert into Static_String1 values (?)";
    PreparedStatement statement=connection.prepareStatement(sql);
    //String str = new String("\u05D0\u05D4\u05E5\u05E6\u05D7"); /* This works fine*/
    String str = statString; /*statString is the dynamic string variable containing Hebrew characters... not working*/
    statement.setString(1,str);
    statement.executeUpdate();
    statement.close(); Please let me know how to ensure that the database recognizes that an Unicode string is being inserted.
    Edited by: rajendrabn on Apr 1, 2008 2:41 AM

    rajendrabn wrote:
    JoachimSauer wrote:
    I don't understand that distinction. If your java source file contains the String "\u05D0\u05D4" then it is exactly the same thing as if it contained "&#1488;&#1492;" (as the unicode-escapes are handled by the Java compiler, so your class file already contains a "real" Unicode String).Ideally speaking, what you are saying is true, but unfortunately this is not happening.It is true. The only way where it's not true is when you use the Unicode characters directly in your source code (without escapes) and compile using the wrong encoding, but that's not the problem here.
    If it has anything to do with my string variable not being unicode encoded? Right now I am assuming by default java treats all string variables as UNICODE format.Every String is in Unicode in Java (UTF-16 in fact). What might have happened is that you interpreted some bytes wrongly in some initial place and the Unicode that's stored in the String is not what you wanted it to be.
    Try to create a Hexdump of the UTF-16 values of your String (do String.toHexString() for each character (charAt(i))) and check if the values returned are indeed the unicode code points that you expect (somewhere around 5D0) or something else (in which case you have some error earlier in your code).

  • Help.......preparedStatement problem

    hi experts,
    i have this simple bean for inserting data into the database...........................
    // EmployeeDataBaseBean.java
    package wh;
    import java.lang.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmployeeDatabaseBean
    String email = "";
    String empname = "";
    String extno = "";
    String cellno = "";
    String remarks = "";
    HttpServletRequest request = null;
    Connection dbConn = null;
    * Set the request object. This is used for getting parameters.
    public void setRequest(HttpServletRequest request)
         this.request = request;
    }//public void setRequest(HttpRequest request)
    * Connect to the database.
    public void connectToDatabase()
         throws Exception
         /* Use JDBC to connect to the SAMPLE database.*/
         Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
         String url = "jdbc:db2:one";
         String dbUser = "";
         String dbPass = "";
         Connection dbConn = DriverManager.getConnection(url);
         /* If the connection fails, throw an Exception.*/
         if(dbConn == null)
         throw new Exception("The database connection failed.");
         System.out.println("called connect inside connnecttodatabase");
    * Run the SELECT statement query to return a single EMPLOYEE record.
    public void runQuery()
         throws Exception
         /* Connect to the database.*/
         connectToDatabase();
         /* Get the EMPNO parameter from the request object.*/
         String empmailParam = request.getParameter("EMAIL");
         /* Build a SQL SELECT statement.*/
         String sql = "SELECT EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS " +
                                  "FROM CONTACT WHERE EMAIL = ?";
         /* Prepare the SELECT statement.*/
         PreparedStatement statement = dbConn.prepareStatement(sql);
         /* Set the parameter in the SELECT statement and run it.*/
         statement.setObject (1, empmailParam);
         ResultSet result = statement.executeQuery();
         /* Get the result row.*/
         while(result.next())
         email = result.getString("EMAIL");
         empname = result.getString("EMP_NAME");
         extno = result.getString("EXT_NO");
         cellno = result.getString("CELL_NO");
         remarks = result.getString("REMARKS");
         /* Close the connection.*/
         dbConn.close();
    * Insert a record to the database.
    public void insertEmployee()
         throws Exception
         /* Connect to the database.*/
         connectToDatabase();
    System.out.println("connected to db2 through insertemployee");
         /* Get all the parameters from the calling HTML form.*/
         String mailParam = request.getParameter("EMAIL");
         System.out.println("the email is " + request.getParameter("EMAIL"));
         String nameParam = request.getParameter("EMPNAME");
         System.out.println("the name is " + request.getParameter("EMPNAME"));
    int extnoParam = Integer.parseInt(request.getParameter("EXTNO"));
         System.out.println("the extension number is " + request.getParameter("EXTNO"));
         int cellnoParam = Integer.parseInt(request.getParameter("CELLNO"));
         System.out.println("the cellno is " + request.getParameter("CELLNO"));
         String remarksParam = request.getParameter("REMARKS");
    System.out.println("the remark is " + request.getParameter("REMARKS"));
    System.out.println("building sql query");
         /* Build a SQL INSER statement.*/
         String sql = "INSERT INTO CONTACT " + "(EMAIL, EMP_NAME, EXT_NO, CELL_NO, REMARKS) " + " VALUES " +     "(?,?,?,?,?)";
         System.out.println("executed sql statement");
         /* Prepare the SELECT statement.*/
         PreparedStatement statement = dbConn.prepareStatement(sql);     
    System.out.println("using preparedstatement");
         /* Set the parameters for the INSERT run it.*/
         statement.setString(1, mailParam);
         statement.setString(2, nameParam);
         statement.setInt(3, extnoParam);
         statement.setInt(4, cellnoParam);
         statement.setString(5, remarksParam);
         boolean returnValue = statement.execute();
         /* Close the connection.*/
         dbConn.close();
         System.out.println("query executed");
    }//public void insertEmployee()
    * Return the empNo.
    public String getemail()
         return email;
    * Return the firstNme.
    public String getempname()
         return empname;
    * Return the midInit.
    public String getextno()
         return extno;
    * Return the lastName.
    public String getcellno()
         return cellno;
    * Return the edLevel.
    public String getremarks()
         return remarks;
    //and the html page calling the jsp page which inturn uses the bean.
    //EmployeeInput.html
    <HTML>
    <HEAD>
    <TITLE>
    Employee Input
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#f0f0ff">
    <H2>Insert An Employee:</H2>
    <BR><FORM NAME="employeeForm" ACTION="EmployeeDisplay.jsp">
    <table border=2>
    <tr>
    <td>EMail:</td>
    <td><INPUT NAME="EMAIL" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Employee Name:</td>
    <td><INPUT NAME="EMPNAME" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Extension Number:</td>
    <td><INPUT NAME="EXTNO" VALUE="" TYPE="text" LENGTH="6"></td>
    </tr>
    <tr>
    <td>Cell Number:</td>
    <td><INPUT NAME="CELLNO" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td>Remarks:</td>
    <td><INPUT NAME="REMARKS" VALUE="" TYPE="text"></td>
    </tr>
    <tr>
    <td><center><INPUT NAME="submitButton" VALUE="Insert" TYPE="submit"></center></td>
    </tr>
    </FORM>
    </BODY>
    </HTML>
    // the jsp page that uses the bean.
    //EmployeeDisplay.jsp
    <jsp:useBean id="employeeDatabaseBean" class="wh.EmployeeDatabaseBean" scope="request"/>
    <!-- Perform the actions on the bean. -->
    <%
    try
    /* Set the request object.*/
    /* The request object is implicitly available in the JSP page.*/
    employeeDatabaseBean.setRequest(request);
    /* Insert the employee data into the database.*/
    employeeDatabaseBean.insertEmployee();
    /* Run the query to retrieve the employee data from the database.*/
    //employeeDatabaseBean.runQuery();
    catch (Exception e)
    System.out.println(e.getMessage());
    %>
    <HTML>
    <HEAD>
    <TITLE>
    Employee Display
    </TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF">
    <H2>Employee Record:</H2>
    <BR><FORM NAME="employeeDisplayForm" >
    <BR>Employee No: <INPUT NAME="EMPNO" VALUE="<%= employeeDatabaseBean.getemail() %>" TYPE="text">
    <BR>First Name: <INPUT NAME="FIRSTNME" VALUE="<%= employeeDatabaseBean.getempname() %>" TYPE="text">
    <BR>Mid: <INPUT NAME="MIDINIT" VALUE="<%= employeeDatabaseBean.getextno() %>" TYPE="text" LENGTH="4">
    <BR>Last Name: <INPUT NAME="LASTNAME" VALUE="<%= employeeDatabaseBean.getcellno() %>" TYPE="text">
    <BR>Education Level: <INPUT NAME="EDLEVEL" VALUE="<%= employeeDatabaseBean.getremarks() %>" TYPE="text">
    </FORM>
    </BODY>
    </HTML>
    my problem is that the file runs perfectly on the browser. The issue arises here that the data doesnt gets inserted into the database...................also that the console does not show any error either........what i feel is that the prepared statement isnt functioning properly.......the control doesnt moves beyond the prepared statement
    plz help

    You have defined a Connection object in the beginning of the class. And then you wrote the following connection in a function:
    /* Use JDBC to connect to the SAMPLE database.*/
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
    String url = "jdbc:db2:one";
    String dbUser = "";
    String dbPass = "";
    /**************************************//Problem is here */
    Connection dbConn = DriverManager.getConnection(url);
    /* If the connection fails, throw an Exception.*/
    if(dbConn == null)
    throw new Exception("The database connection failed.");
    System.out.println("called connect inside connnecttodatabase");
    Since you are trying the create the object inside the function. Here you said:
    Connection dbConn = DriverManager.getConnection(url);
    In this code dbCon cannot to point to your class level ( which you have defined in the declaration section) dbConn object. Hence this dbConn treated as local memeber to this function. That's it.
    Regards,
    Sudheer Varma Dandu

  • PreparedStatement not working

    Hi,
    I am having some problem using PreparedStatement.executeUpdate() . I want to be able to prepare several queries before commiting and I wrote this just to test it
    PreparedStatement stmt= aConnection.prepareStatement("update trans_test1 set field1='a text field' where field1='other text'");
              stmt.executeUpdate();
              aConnection.commit();
              stmt.close();
              aConnection.close();
    when it hits this line "stmt.executeUpdate();" the program just stops running and after a while throws this error.
    java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
    I set the auto commit to false but I still can't get it working and do not understand the problem. Any one can help?
    Thanks so much
    Alejo

    Hi,
    I am having some problem using
    PreparedStatement.executeUpdate() . I want to be able
    to prepare several queries before commiting and I
    wrote this just to test it
    PreparedStatement stmt=
    aConnection.prepareStatement("update trans_test1 set
    field1='a text field' where field1='other text'");
              stmt.executeUpdate();This is wrong in so many ways:
    (1) Use the bind variables.
    (2) Close resources properly in a finally block.
    (3) You don't show where you set auto commit to false
    (4) You don't show where you rollback in the event of a failure.
    >
    I set the auto commit to false but I still can't get
    it working and do not understand the problem. Any one
    can help?A snippet like this isn't enough. Post all the code.
    Which database are you using, and which driver?
    %

  • Can someone help me correct this sql statement in a jsp page?

    ive been getting the java.sql.SQLException: Incorrect syntax error for one of my sql nested statements. i cant seem to find similar egs online, so reckon if anyone here could help, really appreciate it.
    as im putting the nested sql in jsp page, it has to be with lots of " " n crap. very confusing if there are nested.
    heres the sql statement without those "" that i want to use:
    select top 5 * from(
    select top+"'"+offset+"'"+" * from prod where cat=" +"'" cat "'"+"
    )order by prodID desc
    when i put this in my jsp pg, i had to add "" to become:
    String sql = "select top 5 * from("+"select top"+"'"+offset+"'"+" * from prod where cat=" +"'" +cat+ "'"+")order by prodID desc";cat=" +"'" cat "'"+")order by prodID desc";
    all those "" are confusing me to no end, so i cant figure out what should be the correct syntax. the error says the syntax error is near the offset.

    If offset is, say, 10, and cat is, say, "new", then it looks like you're going to produce the SQL:
    select top 5 * from(
      select top '10' * from prod where cat='new'
    )order by prodID descThat looks exactly like incorrect syntax to me... top almost certainly can't handle a string literal as its operand... you almost certainly would want "top 10" instead of "top '10'"...
    If you use PreparedStatement, you don't have to remember what you quote and what you don't and you can have your SQL in a single static final string to boot...

Maybe you are looking for

  • IF statement in RB2.0

    I am trying to use an IF logic statement in a report but as an expression, I have been searching the net to help me find an answer as everything I have tried is sending an error when I run   The report feeds from multiple tables and has various filte

  • Firewall and Internet Sharing dont mix

    After talking to AppleCare, looks like my firewall is not letting me sync to my AppleTV because I am using Internet Sharing to connect it to my Mac Mini (PPC) and get to the internet through the Mini's ethernet. I have no Airport Express or Extreme.

  • Export 3D grid structure from Photoshop to Illustrator

    Hi everyone, I have Photoshop CS4 Extended and have created a 3D sphere using the 3D menu. Under the render settings I have it set to edge style so that all you're seeing is the grid structure that makes up the object. I would like to be able to expo

  • SAN already in use FCP X

    Hi, Please can some one help? I have just taken a SW update to FCP X and now my projects are not loading and I get an error saying SAN already in use... Is there anyway around this? Thanks... /John

  • Oracle 9iR2 in RHLE3 AS (patches problem)

    Hi! I need a couple of patches to Install Oracle 9i R2 in my Red Hat Enteprise Linux 3 AS Server. I know that they are in metalink, but I do not access to those pages. The files needed are: p2617419_210_GENERIC.zip p3006854_9204_LINUX.zip p3119415_92