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

Similar Messages

  • 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

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

  • PreparedStatement space and empty String

    Hi, I have this problem:
    PreparedStatement bookedQtyPS = null;
    String qry="SELECT * from djwsearch where djwitem=?;
    bookedQtyPS = conn.prepareStatement(qry);
    if(item.equals(""){ //item is an empty String
    bookedQtyPS.setString(1," "); // I set space instead of empty String
    }else{
    bookedQtyPS.setString(1,item);
    My problem is that I need to set space insteadOf empty String, but I think that I can not use PreparedStatement to do this. I have performance problems (my query is much more complicated than this one) so I choose PreparedStatement and not Statement.
    How can I do? Is this bug solved using PreparedStatement?
    Thanks.

    you can do it with the help of PreparedStatement.
    Here the type of field(djwitem) and setmethod is should be match..i mean if the type of ur field is String then you need to use the setSting method.
    you can do one thing specify one string variable.
    String space=" ";
    and now put this sapce variable at the second parameter of setString method.

  • Help with JDBC

    When i use the following:
    stmt.executeUpdate("INSERT INTO Car " + "VALUES (" + temp + ", " + carData[0] + ", " + carData[1] + ", " + carData[2] + ", " + carData[3] + ", " + carData[4] + ", " + carData[5] + ", " + carData[6] + ", " + carData[7] + ", " + carData[8] + ", " + carData[10] + ", " + carData[11] + ", " + carData[12] + ", " + carData[9] + ", " + carData[13] + ", " + carData[14] + ", " + carData[15] + ", " + carData[16] + ", " + carData[17] + ", " + carData[18] + ", " + carData[19] + ", " + carData[20]+")");
    i get the following error message:
    SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression 'Audi A2 (Standard & SE)'.
    where: 'Audi A2 (Standard & SE)' is the value stored in carData[4].
    Can anyone help?

    I keep getting an array index out of bounds now. The array is of size 21. Can you help?
    PreparedStatement storeCarValues = con.prepareStatement("INSERT INTO Car " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    storeCarValues.setInt(1, temp);
    for(int i=0; i<21; i++)
    System.out.println(i);
    storeCarValues.setString(i+2, carData);
    storeCarValues.executeUpdate();

  • Problem in JDBC

    Hiii all,
    i want to make a page for username and password and i connected it with a database that contains the usernames and passwords
    now i want to know how can i make a query (select password from table where username=the string that the user enter it) to match it with the password which i have in the database i write in the class:
    static final String JDBC_DRIVER="sun.jdbc.odbc.JdbcOdbcDriver";
    static final String DATABASE_URL="jdbc:odbc:Fees"
    and in the try i write:
    Class.forName(JDBC_DRIVER);               
    connection= DriverManager.getConnection(DATABASE_URL);
    statement= connection.createStatement();
    get=Integer.parseInt(textField1.getText());          
    ResultSet result=statement.executeQuery("SELECT Password FROM Fees WHERE Fees.StudentNo='"+get+"';");
    but thats wrong, can anybody help me

      PreparedStatement name= connection.prepareStatement("SELECT StudentName FROM Fees WHERE StudentNo=ID");That SQL statment will get all the rows from the Fees table where the column named StudentNo is equal to the column named ID; if those 2 columns don't exist, then you should get a SQLException, which you should by catching and printing because it will almost certainly give you a clue that your code is bad.
    What I'm guessing you want is:
      PreparedStatement name= connection.prepareStatement("SELECT StudentName FROM Fees WHERE StudentNo=?");
      name.setString(1,ID);
      ResultSet result=name.executeQuery();If the StudentNo column is a of a numeric type in the database, then the ID variable should be converted in your Java code (where you can more gracefully deal with conversion errors) to an appropriate numeric type, such as int, and you should call the appropriate set method for that numeric type, such as setInt().
    By the way, notice how more readable the code is in my post, compared to yours; that's done by using the code button (or typing in the tags manually), and if you continue to post here, you should start to use it as a courtesy to the people you volunteer their time to answer your questions.

  • Problem with using Postgres database in java.

    Hi ,
    I am using netbean netbean IDE 6.1.5 and postgres as my database.
    I want to pass a date to a query in java like-
    "select count(\"JOBID\") from emp
    to_char(\"STARTTIME\",'yyyy-MM-dd')=" + datestr
    where STARTTIME is a date field,
    but when I run the program it gives the error
    error: operator does not exist: text = integer
    even if I use this query
    ResultSet result1= stmt.executeQuery("select count(\"JOBID\") frrom emp "+
    " where to_date(\"STARTTIME\",'YYYY-MM-DD HH:MI:SS')=" + sqlDate);
    WHERE STARTDATE is string and
    sqlDate=java.sql.Date sqlDate
    it gives
    error:error: operator does not exist: date = integer
    please help
    moni

    Use PreparedStatement instead of Statement all the way. Not only it is faster and saves you from any SQL injection risks, but it also eases setting complex Java objects in a SQL query. It has for example a setDate() method.
    Prepare here: [http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html].

  • Problem with SQL query never completing

    Right I have a piece of code which executes an SQL query but no matter what I do the program always hangs whenever it gets to the SQL execute line, I have tried using stmt.execute, executeUpdate and executeQuery and none work.
    I can however connect to the database directly and run the same query and it works fine, would be really grateful for some help.
    Code snippet is below, and works is never printed to the command line.
           SQLString = "INSERT INTO TH.OUTPUT_DATA_SNAPSHOT_HDR_TH " +
                    "( EXEC_DATE, USER_ID, OUTPUT_STYLE, OUTPUT_DATE, " +
                    "OUTPUT_FILENAME, SPARE_CHAR_01, SPARE_CHAR_02, " +
                    "SPARE_CHAR_03, SPARE_CHAR_04, SPARE_CHAR_05, " +
                    "SPARE_CHAR_06, SPARE_CHAR_07, SPARE_CHAR_08, " +
                    "SPARE_CHAR_09, SPARE_CHAR_10, SPARE_DATE_01, " +
                    "SPARE_DATE_02, SPARE_DATE_03, SPARE_DATE_04, " +
                    "SPARE_DATE_05, SPARE_DATE_06) " +
                    "VALUES " +
                    "('" + OutExec_Date + "', '" +                     // Exec_Date
                    String.valueOf(DatabaseProperties.AppUserID) +     // User ID
                    "', '" + OutputStyle + "', " +                     // Output_Style
                    "'" + OutputDate + "', " +                         // Output_Date
                    "'" + GlobVarStore.CopyInvDirectory + "', "+       // Output_Filename
                    "'', " +                                           // Spare_Char_01
                    "'', " +                                           // Spare_Char_02
                    "'', " +                                           // Spare_Char_03
                    "'', " +                                           // Spare_Char_04
                    "'', " +                                           // Spare_Char_05
                    "'', " +                                           // Spare_Char_06
                    "'', " +                                           // Spare_Char_07
                    "'', " +                                           // Spare_Char_08
                    "'', " +                                           // Spare_Char_09
                    "'', " +                                           // Spare_Char_10
                    "'" + OutputDate + "', " +                         // Spare_Date_01  - Must not be null
                    "'" + OutputDate + "', " +                         // Spare_Date_02
                    "'" + OutputDate + "', " +                         // Spare_Date_03
                    "'" + OutputDate + "', " +                         // Spare_Date_04
                    "'" + OutputDate + "', " +                         // Spare_Date_05
                    "'" + OutputDate + "'" +                           // Spare_Date_06
           Statement stmt = DatabaseProperties.DBConnection.createStatement();
           System.out.println(SQLString);
           stmt.executeQuery(SQLString);
           System.out.println("works");

    Right I didn't know what a prepared statement was so have done a bit of research and come up with the following code, seems to give same error.
    I know the connection is working because other SQL code is executing in program before it gets to this point, have included the actual SQL statement as well.
    Cheers for your help
           try
              PreparedStatement prepStmt = DatabaseProperties.DBConnection.prepareStatement("INSERT INTO TH.OUTPUT_DATA_SNAPSHOT_HDR_TH ( EXEC_DATE, USER_ID, OUTPUT_STYLE, OUTPUT_DATE, OUTPUT_FILENAME, SPARE_CHAR_01, SPARE_CHAR_02,SPARE_CHAR_03, SPARE_CHAR_04, SPARE_CHAR_05,SPARE_CHAR_06, SPARE_CHAR_07, SPARE_CHAR_08,SPARE_CHAR_09, SPARE_CHAR_10, SPARE_DATE_01,SPARE_DATE_02, SPARE_DATE_03, SPARE_DATE_04, SPARE_DATE_05, SPARE_DATE_06) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?)");
              prepStmt.setString(1,OutExec_Date);
              prepStmt.setString(2, String.valueOf(DatabaseProperties.AppUserID));
              prepStmt.setString(3,OutputStyle);
              prepStmt.setString(4,OutputDate);
              prepStmt.setString(5,GlobVarStore.CopyInvDirectory);
              prepStmt.setString(6,"");
              prepStmt.setString(7,"");
              prepStmt.setString(8,"");
              prepStmt.setString(9,"");
              prepStmt.setString(10,"");
              prepStmt.setString(11,"");
              prepStmt.setString(12,"");
              prepStmt.setString(13,"");
              prepStmt.setString(14,"");
              prepStmt.setString(15,"");
              prepStmt.setString(16,OutputDate);
              prepStmt.setString(17,OutputDate);
              prepStmt.setString(18,OutputDate);
              prepStmt.setString(19,OutputDate);
              prepStmt.setString(20,OutputDate);
              prepStmt.setString(21,OutputDate);
              System.out.println(prepStmt.toString());
              prepStmt.executeUpdate();
              System.out.println("works");
           catch(SQLException SQLe)
              SQLe.printStackTrace();
    INSERT INTO TH.OUTPUT_DATA_SNAPSHOT_HDR_TH ( EXEC_DATE, USER_ID, OUTPUT_STYLE, OUTPUT_DATE, OUTPUT_FILENAME, SPARE_CHAR_01, SPARE_CHAR_02, SPARE_CHAR_03, SPARE_CHAR_04, SPARE_CHAR_05, SPARE_CHAR_06, SPARE_CHAR_07, SPARE_CHAR_08, SPARE_CHAR_09, SPARE_CHAR_10, SPARE_DATE_01, SPARE_DATE_02, SPARE_DATE_03, SPARE_DATE_04, SPARE_DATE_05, SPARE_DATE_06) VALUES ('09/09/2009', '200', 'INVOICE', '16/09/2009', 'C:\Users\aaronh\DOC20090916163456.txt', '', '', '', '', '', '', '', '', '', '', '16/09/2009', '16/09/2009', '16/09/2009', '16/09/2009', '16/09/2009', '16/09/2009')

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

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

Maybe you are looking for

  • How to move rows up and down on a SharePoint List Item

    Hello, I have created a simple Project Plan Template for my team using a SharePoint list. I have listed a sample below:      Date                               Tasks                                                    Owner 03/09/14                  

  • Need Programming Help - Changing Algorithm for PhotoShop's Oil Paint Plug-In Filter

    The existing PhotoShop Oil Paint filter only works well when applied to relatively small image sizes of around 500kb. I need to apply these effects to relatively large image sizes of around 100mb. I do not have a background in programming, but to my

  • Making DVD with no menu - immediately plays?

    Is there a way to make a DVD so that it plays when you insert the DVD into the player? I usually make a DVD menu, but I have something that won't need a menu and will play on a loop. Any tips?

  • UDF delition error

    Hi       While deleting UDF i am getting error  invalid column name.'Item' (UITM) (CINF) this error is coming after i upgrade my SAP B1 PL00 to PL08. Please advice me Warm Regards Rahul

  • Media Applications Not working

    I have BB 9300 with OS 6.. My media applications are not working. Whenever I take any picture. It becomes corrupt. Similarly whenever I made any movie it also becomes corrupt. Interesting part is that file properties are correct but not even open in