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

Similar Messages

  • 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);

  • PreparedStatement vs. Statement

    Is PreparedStatement always better than Statement?
    My idea is, PreparedStatement is more efficient when in a loop. (Is this correct?)
    But when I read some code, the author always uses PreparedStatement, as if it is preferred no matter what.
    Can you let me know if there are differences? Thanks!

    While there are certainly times to use Statement, beginners should always start with PreparedStatement, using bind variables.
    With Oracle and many other databases, PreparedStatement with bind variables will give you improved perfromance on subsequent execution of the SQL (as long as it's an EXACT string match), even when the following executions are hours, minutes, or even days later, even by a different program. This benefit comes from the database caching the execution plan for the SQL. The execution plan is the result of parsing and evaluating the SQL and is somewhat analogous to compiling a program file. Just as you don't want to compile every time you execute a program, so you also don't want to parse and evaluate every time you submit a SQL statement. Bind variables in PreparedStatements helps you do that.
    The variability on how long the database will cache your execution plan comes from the fact that the cache is a fixed size LRU (least recently used) cache. SQL that is used infrequently ages out of the cache and how frequently depends on how much different SQL gets seen by the different database. SQL is "different" if it's not an exact string match (including case and any non-bound data values embedded in it) to something already in the cache. This means that using bind variables with PreparedStatement not only tends to speed up performance for that SQL, it also helps to improve performance on busy databases for everything else by reducing the amount of "different" SQL, thereby increasing the length of time other infrequently used SQL stays in the cache, and thereby improving the cache hit ratio on this LRU cache.
    Additionally, PreparedStatement with bind variables helps prevent "SQL injection" attacks, a significant problem of naively programmed web sites. Search the web for detailed explanations, there's plenty of them.
    Finally, PreparedStatement with bind variables can make your life easier. Many beginners try to code dynamically built SQL, such as:
    String sql = "SELECT * FROM user_data WHERE last_name = '" + lastName + "'";Ignoring SQL injection attacks, that works OK until:
    String lastName = "O'Conner";The quote embedded in the name gets matched to first quote after the = in the SQL, and the SQL is broken upon execution. You either need to check all your data to see if it needs to haven embedded quotes escaped, or you use PreparedStatement and bind variables.
    There are some SQL statements where, as far as I know, it doesn't matter much, e.g. DDL statements (table creation and the like) and connection altering statements, such as "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYYMMDD HH24:MI'". I'm not sure either is cached, or if caching has any benefit; even if it is and there is, the SQL doesn't vary...
    There are some very very rare times when (at least on Oracle), using a bind variable can increase the execution time for some values of the variable; the problem is very rare and is almost always caused by data skew; for most values of that bind variable, the correct thing to do is scan all the data in the table, but for a very few values, the correct thing is to use an index to look up the needed rows. When bind variables are used for that variable, the execution for the "typical" case is picked; if the SQL has the bind variable replaced with an actual value, the optimizer can see that for those few particular values, the index lookup is faster and will use that. This data skew problem commonly comes up with "job status" flags on tables that hold both "in progress" and "completed" jobs. Eventually, the "completed" jobs are 99.99 percent of the data, and find the non-completed ones gets slower than it should be.
    Beginners should use PreparedStatements until they understand the exceptions or run into performance problems.

  • Utility method

    I know PreparedStatements help prevent SQL injection and ticks.
    The only thing I notice is it doesnt handle greater than and less than such as < with a > entry in a form. When they are entered into a form that populates oracle it seems to disappear when I view the record on a web page.
    I can create a Utility method to handle this and was wondering if this is what others do to handle < with a > form entries?

    Escape it into an HTML entity when displayed.

  • 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();

  • 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 ;-)

  • 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

  • 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?

  • 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...

  • Too many connections - even after closing ResultSets and PreparedStatements

    I'm getting a "Too many connections" error with MySQL when I run my Java program.
    2007-08-06 15:07:26,650 main/CLIRuntime [FATAL]: Too many connections
    com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812)
            at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269)
            at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182)
            at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670)I researched on this and found out that I wasn't closing the ResultSet and the PreparedStatement.
    The JDBC connection is closed by a central program that handles connections (custom connection pooling).
    I added the code to close all ResultSets and PreparedStatements, and re-started MySQL as per the instructions here
    but still get "Too many connections" error.
    A few other things come to mind, as to what I may be doing wrong, so I have a few questions:
    1) A few PreparedStatements are created in one method, and they are used in a 2nd method and closed in the 2nd method
    does this cause "Too many connections" error?
    2) I have 2 different ResultSets, in nested while loops where the outer loop iterates over the first ResultSet and
    the inner loop iterates over the second ResultSet.
    I have a try-finally block that wraps the inner while loop, and I'm closing the second ResultSet and PreparedStement
    in the inner while loop.
    I also have a try-finally block that wraps the outer while loop, and I'm closing the first ResulSet and PreparedStatement
    in the outer while loop as soon as the inner while loop completes.
    So, in the above case the outer while loop's ResultSet and PreparedStatements remain open until the inner while loop completes.
    Does the above cause "Too many connections" error?
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The following is relevant sections of my code ( it is partially pseudo-code ) that shows the above 2 cases:
    init( Connection jdbcConnection ){
       String firstSQLStatement = "....";
       PreparedStatement ps1 = jdbcConnection.prepareStatement( firstSQLStatement );
       String secondSQLStatement = "....";
       PreparedStatement ps2 = jdbcConnection.prepareStatement( secondSQLStatement );
       String thirdSQLStatement = "....";
       PreparedStatement ps3 = null;
       ResultSet rsA = null;
       try{
            ps3 = jdbcConnection.prepareStatement( thirdSQLStatement );
            rsA = ps3.executeQuery();
            if( rsA.next() ){
                   rsA.getString( 1 );
       }finally{
            if( rsA != null )
                   rsA.close();
            if( ps3 != null )
              ps3.close();
       //Notice, how ps1 and ps2 are created here but not used immediately, but only ps3 is
       //used immediately.
       //ps1 and ps2 are used in another method.
    run( Connection jdbcConnection ){
         ResultSet rs1 = ps1.executeQuery();
            try{
               while(rs1.next()){
                    String s = rs1.getString();
                    ps2.setString(1, s);
              ResultSet rs2 = ps2.executeQuery();
                    try{
                   while(rs2.next()){
                        String s2 = rs2.getString();
                    }finally{
                   if( rs2 != null )
                     rs2.close();
                   if( ps2 != null )
                     ps2.close();
         }catch( Exception e ){
              e.printStackTrace();
         }finally{
            if( rs1 != null )
                  rs1.close();
               if( ps1 != null )
                  ps1.close();
    //Notice in the above case rs1 and ps1 are closed only after the inner
    //while loop completes.
    }I appreciate any help.

    Thanks for your reply.
    I will look at the central connection pooling mechanism ( which was written by someone else) , but that is being used by many other Java programs others have written.
    They are not getting this error.
    An addendum to my previous note, I followed the instructions here.
    http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html
    There's probably something else in my code that is not closing the connection.
    But I just wanted to rule out the fact that opening a PreparedStatement in one method and closing it in another is not a problem.
    Or, if nested ResultSet loops don't cause the problem.
    I've read in a few threads taht "Too many connections" can occur for unclosed RS and PS , and not just JDBC connections.

Maybe you are looking for

  • How to remove upcoming events from iCal's day view

    Is there any way to remove the Upcoming Events list (on the left) from the Day view in iCal? They are distracting!

  • NHK programming off by 1 hour (3rd year in a row!)

    At least the guide people are consistent.  Yet again this year, they failed to take into account that the international channels (like NHK) to not follow daylight savings time.  Yet again this year I'm forced to get the accurate schedule off the NHK

  • Movie taking up more space than the size

    Hello. I published a movie in imovie to the media gallery in HD. It is a long video, so I knew it would take up a lot of space. It is listed as 5 GB in my imovie project folder. However, when I "show package contents" of the movie, the actual size of

  • Apple TV 2 reset and update to iOS 5 not possible

    I can't upgrade my ATV 2 to iOS 5.0. I tried both ways described at support.apple.com. At ATV a message says it is not possible.... try again later. When I connect ATV with a micro USB to my iMac, iTunes 11 does not recognize the ATV, so Im not able

  • Folders don't open

    some of the folders i have in bookmarks don't open when i go with the pointer over them.some work fine ,some don't.