PreparedStatement Syntax

If i've 2 preparedStatement which needs to be executed simultaneously>>
'SELECT * FROM EMPLOYEE WHERE FIRSTNAME=? AND LASTNAME=?'
'SELECT * FROM WORK WHERE TITLE=? AND LOCATION=?'
How can i do it?? Is it>>
pstmt.setString(1, value1);
pstmt.setString(2, value2);
pstmt.setString(3, value3);
pstmt.setString(4, value4);
Do i need to use pstmt.addBatch()??
If yes, pls teach me how to use it. (I'm new to preparedStatement) Thanks a zillion!

As you have got two prepared statements one option I suggest would be to declare two prepared staments and execute each statement simultaneously. Like...
pstmt.setString(1, value1);
pstmt.setString(2, value2);
pstmt1.setString(1, value3);
pstmt2.setString(2, value4);
and execute them.
May be thgis helps you...

Similar Messages

  • PreparedStatment creating Syntax Error.

    The poblem is in the first prepared statment if I enter the value straight into the statement string everying works fine. However, when I use a ? for placeholder and then supply the same sting value i would have entered in the statement string I get a sytax error.
    import java.sql.*; import javax.swing.*; import java.awt.BorderLayout; import java.awt.event.*; public class Exercise34_5 extends JFrame { private JTextField jtfInput = new JTextField(10); private JButton jbShowTable = new JButton("Show Table"); private JTextArea jta = new JTextArea(); private PreparedStatement pstmt1; private PreparedStatement pstmt2; private PreparedStatement pstmt3; public Exercise34_5() { JPanel northPanel = new JPanel(); northPanel.add(new JLabel("Table Name")); northPanel.add(jtfInput); northPanel.add(jbShowTable); add(northPanel, BorderLayout.NORTH); add(new JScrollPane(jta)); try { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test" , "root", "root"); pstmt1 = connection.prepareStatement("describe ?"); pstmt2 = connection.prepareStatement("select count(*) from enrollment"); pstmt3 = connection.prepareStatement("select * from enrollment"); }catch(Exception ex) { ex.printStackTrace(); } jbShowTable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String table = jtfInput.getText(); try{ pstmt1.setString(1, "enrollment"); /*pstmt2.setString(1, "enrollment"); pstmt3.setString(1, "enrollment");*/ ResultSet rset1 = pstmt1.executeQuery(); ResultSet rset3 = pstmt3.executeQuery(); int count = 0; while(rset1.next()) { jta.append(rset1.getString(1) + "\t"); count++; } jta.append("\n"); System.out.println(count); while(rset3.next()) { for(int i = 1; i <= count; i++) { jta.append(rset3.getString(i) + "\t"); } jta.append("\n"); } }catch(Exception ex) { ex.printStackTrace(); } } }); } public static void main(String[] args) { Exercise34_5 frame = new Exercise34_5(); frame.setSize(400, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setVisible(true); } }
    java.sql.SQLException: Syntax error or access violation message from server: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''enrollment'' at line 1"
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:1997)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1167)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1278)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:2251)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1586)
    at Exercise34_5$1.actionPerformed(Exercise34_5.java:47)

    Alyosha wrote:
    I don't understand.You can't just put a ? parameter any old place in a prepared statement. It's just just a simple string substitution. For instance, you cannot use a ? parameter for a table name or a column name.
    // wrong
    ps = conn.prepareStatement("select * from ? where ? = ?");
    ps.setString(1, tableName);
    ps.setString(2, columnName);
    ps.setString(3, columnValue);
    // right
    ps = conn.prepareStatement("select * from " + tableName = " where " + columnName + " = ?");
    ps.setString(1, columnValue);

  • Syntax for PreparedStatement/MySQL

    I need to read a MySQL data table using a field input from the screen. I do a field.getText() to read the data in, then try to substitute that value into a PreparedStatement. But every time it runs, I throw an SQLException that tells me the syntax of the PreparedStatement is wrong.
    Here is the code:
                    Connection dbase = getConnection();
                    String inputCustNo = customerData.getCustomerNo();
              String query = "SELECT * FROM Customer_table WHERE customer_id = ?";
              PreparedStatement stat = dbase.prepareStatement(query);
              stat.setString(1, inputCustNo);The error is "java.sql.SQLException: You have an error in your SQL syntax ... near '?' "
    But the syntax I used is copied directly from MySQL's site. Anyone else familiar enough with Java/MySQL to help me pin down what's happening?

    I have tried it with both int and String variable types and it still won't work.
    customer_id in the table is an integer. I cast the input into an integer and try it and it gets the same error.
    The getConnection method uses the DriverManager and MySQL's jbdc.
    Here's the stack trace:
    java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2998)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2927)
         at com.mysql.jdbc.Statement.execute(Statement.java:535)
         at AddOrder.getCustList(AddOrder.java:79)
         at AddOrder.actionPerformed(AddOrder.java:42)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • [Microsoft][ODBC Microsoft Access Driver] Syntax error

    I am new to Java. I have tried to write a simple program insert table in Access2002. However, I got the following error,
    ERROR: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement
    My code is as follows,
    import java.lang.*;
    import java.sql.*;
    import java.util.*;
    import java.text.*;
    public class dateconv3 {
    public static void main (String[] args) {
    //Setting up the JDBC-ODBC bridge connection
    String DRIVER_NAME = "sun.jdbc.odbc.JdbcOdbcDriver";
    String CONNECTION_URL = "jdbc:odbc:book1";
    // The JDBC Connection Object
    Connection con = null;
    // The JDBC PreparedStatement object
    PreparedStatement ps = null;
    boolean rc = false;
    try { // try under for loop
    // Get an connection
    Class.forName(DRIVER_NAME).newInstance();
    con = DriverManager.getConnection(CONNECTION_URL);
    SimpleDateFormat formatter = new SimpleDateFormat ("yyyy/mm/dd");
    java.util.Date currentTime_1 = new java.util.Date();
    String dateString = formatter.format(currentTime_1);
    ParsePosition pos = new ParsePosition(0);
    java.util.Date currentTime_2 = formatter.parse(dateString, pos);
    java.sql.Date dCurDate=new java.sql.Date(currentTime_2.getTime());
    System.out.println(dCurDate);
    String userid = "1";
    String booktitle = "Java Servlet Programming";
    int amount = 202;
    String sqltxt="INSERT INTO TRANSLOG ( userid, booktitle, date, amount ) VALUES (?,?,?,?)";
    // Create a statement object that we can execute queries with
    ps = con.prepareStatement(sqltxt);
    ps.setString(1, userid);
    ps.setString(2, booktitle);
    System.out.println(currentTime_2);
    java.sql.Date sqlDate = new java.sql.Date(currentTime_2.getTime());
    System.out.println(sqlDate);
    ps.setDate(3, sqlDate);
    ps.setInt(4, amount);
    System.out.println("INSERT into translog table");
    // Execute the statement
    ps.execute();
    rc = true;
    } catch (Exception ex) {
    // Sent the error
    System.out.println("ex.getMessage() print: " + ex.getMessage());
    } finally {
    try {
    if (ps != null) {
    ps.close();
    if (con != null) {
    // Put the connection back into the pool
    con.close();
    } catch (Exception ex) {
    // Ignore any error here
    The Access has been set to the date format yyyy/mm/dd and I got the following result.
    java dateconv3
    2001-01-04
    Thu Jan 04 00:56:00 CST 2001
    2001-01-04
    INSERT into translog table
    ex.getMessage() print: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement
    Please advise. I got frustrated with such a silly question. Anybody can help me to resolve it.
    Patrick

    INSERT INTO TRANSLOG ( userid, booktitle, date, amount ) VALUES (?,?,?,?)I don't have Access on my computer at home here, but it is quite possible that "date" is a reserved word in Access's version of SQL. If you can change the column name, I'd recommend you do that. Otherwise try changing your SQL code to this:
    INSERT INTO TRANSLOG ( userid, booktitle, [date], amount ) VALUES (?,?,?,?)
    But be warned that this [trick] doesn't work with other databases.

  • SQL Insert Syntax erro !!! please help

    I am getting an a Syntax Error
    Sending query: INSERT INTO Customer (custNo, name, address, date) VALUES ('3001005', 'John Ped', '32 Lake st La', '05/07/2004')
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
    Any clues to this problem would be very helpful ....
       if ( !fields.custNo.getText().equals( "" ) &&
                  !fields.name.getText().equals( "" ) ) {
                  String query = "INSERT INTO Customer (" +
                   "custNo, name, address, date" +
                   ") VALUES ('" +
                   fields.custNo.getText() + "', '" +
                   fields.name.getText() + "', '" +
                   fields.address.getText() +"', '"+
                   fields.startDate.getText() + "')";

    Anybody who uses "DATE" for a column name is asking for trouble. First of all, it's a keyword. Second, it's vague. Is it the customer's birthday? The day they were entered into the system? Change that column name to something more descriptive and not a keyword.
    You'd also be much better off using PreparedStatement. It'll escape all those Strings and Dates for you properly.

  • Can anyone spot the syntax error?

    I've been looking at this for about a day now and can't see the error, which is:
    Insert Failed: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
      public String addSaleList(SaleList sL) {
        try {
          //Gets the connection to customer database.
          Class.forName(Driver);
          Connection myCon = DriverManager.getConnection(Url);
          System.out.println(sL.saleListID + " " + sL.saleID + " " + sL.product
                             + " " + sL.number);
          String sqlQry = "INSERT INTO salelist(saleID, product, number)" +
              "VALUES(?,?,?)";
          PreparedStatement myStmt = myCon.prepareStatement(sqlQry);
          myStmt.setInt(1, sL.saleID);
          myStmt.setString(2, sL.product);
          myStmt.setInt(3, sL.number);
          myStmt.executeUpdate();
          return "Sale confirmed";
        catch (Exception e) {
          System.out.println("Insert Failed: " + e);
          return ("Insert Failed: " + e);
      public class SaleList {
        public int saleListID;
        public int saleID;
        public String  product;
        public int  number;
        public SaleList(int saleListID, int saleID, String product, int number) {
          this.saleListID = saleListID;
          this.saleID = saleID;
          this.product = product;
          this.number = number;
      SaleList saleL = new SaleList(0,10,"b",2);
      lblStatus.setText(sM.addSaleList(saleL));

    Hey this is the stack trace:
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6958)
         at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7115)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3150)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execut(JdbcOdbcPreparedStatement.java:214)
    at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdateJdbcOdbcPreparedStatement.java:136)
         at myproject.SaleModel.addSaleList0 120 a 1
    (SaleModel.java:69)
         at myproject.SalesGUI.actionPerformed(SalesGUI.java:395)
         at java.awt.Button.processActionEvent(Button.java:382)
         at java.awt.Button.processEvent(Button.java:350)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

  • What's the syntax for Insert statement in Servlet?

    I'm trying to insert record into table using servlet. Can you please show me the statement and syntax of how to use it?

    hi
    we can insert in 2 types
    1) to all column insert
    insert into <tablename> values  ( 1,2,3,4...n);
    2) particular column insert
    insert into <tablename> ( col1,col2,col3...n)  values  ( value1 for col1, 2 , 3...n);
    ex:
              PreparedStatement ps = con.prepareStatement ( "insert into billtable (grandtotal,userid,creditno)values( ?,?,? )" );
              //bill table
              ps.setDouble ( 1, 10.50);  //replace this double value with double variable
              ps.setString ( 2, "vijay");
              ps.setLong      ( 3, 1111111111);  
              ps.executeUpdate ();
              ps.clearParameters ();
              ps.close ();More Details refer java with Jdbc concepts

  • Sql syntax in jsp

    Hey All!
    Im trying ot use a a bean to select data from a table where email != ''
    The funny thing is my code works in one couple of jsp/bean but not in another, even though it's the exact same code.
    This works
    The Bean:
    String sql = "SELECT applicantid, firstname, lastname, dob, " +
    "homestreet, homestate, homecity, homezip, " +
    "email, college, major, standing, " +
    "graddate, schstreet, schcity, schstate, " +
    "schzip, schphone, resOne, resTwo, " +
    "resThree, waiver, bioletter, password, " +
    "homephone " +
    "FROM apptest " +
    "WHERE " + filter + " " +
    "ORDER BY " + orderBy;
    The filter is the String "email != ''" and orderBy ="lastname"
    Works perfectly!
    But when I use similar code for another table
    Code:
    String sql = "SELECT providerid, applicantid, pin, title, " +
    "company, firstname, lastname, phone, " +
    "email, recletter " +
    "FROM provtest " +
    "WHERE " + filter + " " +
    "ORDER BY " + orderBy;
    with filter as "email != '' " and orderBy = "lastname"
    I get the following error:
    Error in findRecords ProviderUtility(Syntax error or access violation, message from server: "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1")
    Keep in mind that email != '' (these are single quotes)
    I am really baffled.
    Ike

    "The funny thing is my code works in one couple of jsp/bean but not in another, even though it's the exact same code."
    If it's EXACTLY the same code, what did you need another bean for?
    If you needed a new bean, then it's not exactly the same.
    Why aren't you using PreparedStatement to escape strings and dates for you?
    Believe the engine when it tells you there's a mistake.
    %

  • Doubt in PreparedStatement

    i am using two tables(walk and run - two are linked with forein key) . In my application by using one input form , sending data into these two tables. i used the PreparedStatement with sql qurey as follows:
    PreparedStatement ps=con.prepareStatement("insert into walk(?,?)","insert into run(?)");
    (As per syntax PreparedStatement ps=con.prepareStatement(String sqlstatemnt) --- i just given that as i asumed they didn't mention it is a single statement)
    is this possiable to use , if not who may fetch data inot tables....
    is there any possiabulty to do this with the reference of forein key ids

    i am using two tables(walk and run - two are linked
    with forein key) . In my application by using one
    input form , sending data into these two tables. i
    used the PreparedStatement with sql qurey as
    follows:
    PreparedStatement
    ps=con.prepareStatement("insert into
    walk(?,?)","insert into run(?)");That isn't valid.
    >
    (As per syntax PreparedStatement
    ps=con.prepareStatement(String sqlstatemnt) --- i
    just given that as i asumed they didn't mention it is
    a single statementOne string can contain multiple sql statements depending on your database. The format of that depends on your database.
    The example you have above is two strings, not one.
    >
    is this possiable to use , if not who may fetch
    data inot tables....
    is there any possiabulty to do this with the
    reference of forein key idsI can only guess that you want to retrieve the primary key from the first insertion and use it in the second insertion. Some databases allow that. The syntax depends on your database. You can use the gui tool that comes with your database along with the documentation for your database to determine how to do that.

  • Problems with PreparedStatement when select restrict are byte params

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
    "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Hi,
    sorry, i know i've post this same message by error in "new to java" thread.... (i'm new in the forum... can i delete the wrong comment??)
    The SQLState is 42000 (syntax error), but it doesn't give me much information because i had already searched in google why can be the cause of it, but there are only a few comments about problems like this, without a solution...
    The column poscode in the table positions contains an array of bytes that codify a position in a chess board. I've to use this in the WHERE clause because i'm developing a chess game consulting project where there are millions of different positions and i've to get the games that have the same position in it's position history.
    The code to insert the positions is:
    query = "INSERT INTO positions VALUES "+
         "(null,?,?,default) "+
         "ON DUPLICATE KEY UPDATE qtt_games=qtt_games+1";
    pstmt = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
    pstmt.setBytes(1,bcode);
    pstmt.setByte(2,poscode.getIsWhiteTurn());
    pstmt.executeUpdate();
    which works ok and positions can be seen from mysql browser, but i can't select them using the PreparedStatement..
    I have been searching a lot of information about this problem with no results... this is the why i posted this...
    Any help will be useful, thanks.

  • Problems with PreparedStatement and MySQL selecting bytes

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
         "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Don't cross-post, it's considered rude:
    http://forum.java.sun.com/thread.jspa?threadID=5122604&messageID=9430056#9430056
    http://forum.java.sun.com/thread.jspa?threadID=5122603&messageID=9430050#9430050
    One to a customer, please.
    %

  • PreparedStatement and MySQLSyntaxErrorException

    Hi all,
    I'm trying to insert some data into a mysql table.
    My code is:
    PreparedStatement pstmt = con.prepareStatement(
                            "INSERT INTO ? VALUES (?, ?, ?)");
    pstmt.setString(1, "table");
    pstmt.setByte(2, (byte) 1);
    pstmt.setLong(3, new Date().getTime());
    pstmt.setString(4, sometext);
    pstmt.executeUpdate();But if sometext contains some characters (e.g. ', ", \) I get
    MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''chat_pages' VALUES (1, 1159984359374, '\'')' at line 1What should I do so that it works?
    Thanks reshnesh

    Hi all,
    I'm trying to insert some data into a mysql table.
    My code is:
    PreparedStatement pstmt =
    con.prepareStatement(
    "INSERT INTO ? VALUES (?, ?,
    My guess is that you can't use the replacement value for the "table" part of the SQL
    statement, as the driver is surrounding it with single ticks.
    EDIT: oh, if you're saying sometimes it works and sometimes not, then disregard my post...
    Message was edited by:
    tsith

  • Dynmaic sql for PreparedStatement

    I'm attempting to dynamically generate the where clause of a sql query.
    My code looks something like:
    public void myMethod (String fieldA, Map params) throws SQLException{
    String sql = "select * from tableA a, tableB b where a.field = b.field and a.field = ?"
    Connection con = PoolManager.getConnection();
    Iterator it = params.keySet().iterator();
    while(it.hasNext()){
    String fieldName = (String) it.next();
    sql +="and "+fieldName+" = ? ";
    PreparedStatement pStmt = conn.prepareStatement(sql);
    pStmt.setString(1,fieldA);
    Iterator it2 = params.keySet().iterator();
    for(int i=2;it2.hasNext();i++){
    String fieldName = (String) it2.next();
    Object value = params.get(fieldName);
    if(value instanceof String){
    pStmt.setString(i,(String)value);
    } else if(value instanceof Integer){
    pStmt.setInt(i,((Integer)value).intValue());
    } else if(value instanceof java.sql.Date){
    pStmt.setDate(i, (java.sql.Date)value);
    ResultSet rs = pStmt.executeQuery();
    I'm using resource pooling to get a connection, so that's not my problem.
    The params Map has a keyset of column names paired with values which are objects of various types, for example an entry could be ("a.entryDate",java.sql.Date(2002,1,2));
    If I print out my sql following my while loop, the sql looks good. If I step through the code in a debugger, I set all of the values in the preparedStatement as I expect, it bombs when the executeQuery step is performed.
    The sql exception I get states an incorrect syntax near '?'
    Again, the sql looks fine and ran correctly BEFORE I tried to dynamically build the where query. This is puzzling because if I print out sql statment in either case, they are identical.
    Any help would really be appreciated.
    ddwb

    try the following:
    replace
    sql +="and "+fieldName+" = ? ";with
    sql +=" and "+fieldName+" = ? ";note: there is an additional space at the beginning of the string.

  • PreparedStatement parameter binding

    Hello,
    I am new to JDBC and java technology. I have experience with SQL, PL/SQL and I am quite shocked, that binding parameters using PreparedStatement class is based on parameter index instead of the parameter name.
    It is quite common in PL/SQL to use paramter name to bind a value to it.
    E.g. if I use query "select * from foo where id = :id and name = :name" I can bind parameters using dbms_sql.bind_variable(query, "id", 5) dbms_sql.bind_variable(query, "name", "london").
    However, in java I jave to bind using parameter index e.g query.setInt(1, 5), query.setString(2, new String("london")). Now the problems are
    - what if the sql programmer changes code "select * from foo where id = ? and name = ?" to "select * from foo where name = ? and id = ?"
    - think of a quite more complicated query, e.g. query with size of few kB - there can be a parameter repeated many times (id, date range etc) so I need to bind this parameter many times, instead of simple one bind by name
    - think of a dynamicaly generated query, where it is seriously complicated to follow the parameter indexes (sql block repeating, dynamicaly generated where clausules etc) and again binding by name is much more easier than indexed binding
    So my question is: Do you know of any class that supports binding by name ? Is there any workaround how to solve above mentioned issues ?
    And finally, what is the reason to use parameters by index instead of naming, which is I belive more obvious in database programming ?
    I am looking forward to your answers.
    Kindest regards,
    Kamil Poturnaj
    Mgr. Kamil Poturnaj, MicroStep-MIS
    Ilkovicova 3, 841 04 Bratislava, Slovakia

    - what if the sql programmer changes code "select *
    from foo where id = ? and name = ?" to "select * from
    foo where name = ? and id = ?"Tell him "please stop doing that" :-)
    He could also add a third parameter, "address = ?" which would also break it (even if the "?" were spelled ":address").
    The SQL statement and the code that binds / extracts values need to be modified in sync.
    - think of a quite more complicated query, e.g. query
    with size of few kB - there can be a parameter
    repeated many times (id, date range etc) so I need to
    bind this parameter many times, instead of simple one
    bind by nameThough I'm no great fan of vendor-specific 70-style languages, I'd recommend writing a PL/SQL procedure if a query gets very big.
    So my question is: Do you know of any class that
    supports binding by name ? Is there any workaround how
    to solve above mentioned issues ?I don't know of such a package; anyone...?
    It should be a nice programming exercise to write one. Something like:
        BindStatement stmt = new BindStatement("select a, :id from foo where id = :id and name = :name");
        stmt.set("name", "John");
        stmt.set("id", 1234);BindStatement would need to locate each occurrence of ":X" and create an SQL string with them replaced with "?"s. It would also need to store the positions where each ":X" occurred, so that when set("id",...) is called, it could do set(1,...); set(2,...); for the underlying statement.
    Occurrences of ":X" within strings need to be considered; the easy way is to replace there too.
    Unless I'm missing some gotcha, shouldn't take more than a couple of hours to write.
    And finally, what is the reason to use parameters by
    index instead of naming, which is I belive more
    obvious in database programming ?I can only speak from my experience: sql statements within Java code tend to be simple, and the "?" syntax is quite adequate there. Complex statements, if needed, are hidden in PL/SQL. Large systems use beans and automatically generated sql glue. This seems to be rarely a problem.

  • Servlet database query syntax

    Hi,
    I'm trying to add a search function to a servlet.
    I am able to retreive the value of cof_name with the getParameter() method. However when I try to query the database for that value (cof_name) it doesnt work. Can anyone tell me what is wrong with my sql syntax?
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.sql.*;
    import java.sql.*;
    import java.util.*;
    public class Search extends HttpServlet{
       public void doPost(HttpServletRequest request, HttpServletResponse response)
                                       throws ServletException,IOException{
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          System.out.println("MySQL Connect Example.");
          Connection conn = null;
          String url = "jdbc:mysql://localhost:3306/aubrey?";
          String driver = "com.mysql.jdbc.Driver";
          String userName = "Dude1";
          String password = "supersecret";
          Statement st;
          try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url,userName,password);
            System.out.println("Connected to the database");
            String  cof_name  = request.getParameter("cof_name");
            String  sup_id  = request.getParameter("sup_id");
            String  price  = request.getParameter("price");
            String query = "select  COF_NAME from COFFEES where COF_NAME like 'cof_name'";
            System.out.println("query " + query);
            st = conn.createStatement();
            ResultSet  rs = st.executeQuery(query);
          out.print("<html><head>");
             out.print("</head><body>");
             out.print("<code><pre>");
             out.print("<font color=green>COF_NAME\tSUP_ID ");
             out.println("\t\tPRICE\tSALES\tTOTAL\n</font>");
         while(rs.next()){
            out.print(rs.getObject("COF_NAME").toString()+"\t");
            out.print(rs.getObject("SUP_ID").toString()+"\t\t");
         out.print(rs.getObject("PRICE").toString()+"\t");
         out.print(rs.getObject("SALES").toString()+"\t");
         out.println(rs.getObject("TOTAL").toString());
            conn.close();
            System.out.println("Disconnected from database");
          } catch (Exception e) {
          e.printStackTrace();
    }Regards
    Aubrey.

    1. Don't put business logic in your servlet. A servlet should just be a dispatcher to a business logic layer that has no idea that it's running in a servlet context.
    2. "Doesn't work" means nothing. You have to provide more details.
    3. You're doing select  COF_NAME from COFFEES where COF_NAME like 'cof_name' Note that 'cof_name' is inside your string literal, so Java will not expand that variable. You'd have to do it as "select  COF_NAME from COFFEES where COF_NAME like '" + cof_name+ "'"4. But even that's not the right way. The right way is to use a PreparedStatement.
    String sql = "select  COF_NAME from COFFEES where COF_NAME like ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setString(1, cof_name);
    ResultSet rs = ps.executeQuery();

Maybe you are looking for

  • How do I delete more than 1 bookmark at a time

    I have a gazillion bookmarks, how can I delete more than 1 at a time?

  • No verification code.  I am unable to email photos

    New user of Photshop and getting frustrated as I am unable to email photos.  I do not have a "verification code".

  • Please I had a Problem in my IMAC and if someone can help me

    Interval Since Last Panic Report:  2028273 sec Panics Since Last Report:          14 Anonymous UUID:                    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Sat Jan 26 16:12:32 2013 panic(cpu 1 caller 0xffffff80100b7bd5): Kernel trap at 0xffffff7f915c072

  • Mail confirm messages; rules

    Is there any way of getting rid of mail confirmation messages; for example, when I want to bounce a message, I shouldn't have to see a dialog box every time. After all, I can delete a message without having to see a confirmation dialog box. Is there

  • Runs slow, spinning wheel of death comes often..

    I have an early MacBook Pro Code Duo laptop. 2 Ghz, 2Gigs of RAM. Since loading Snow Cat it seems to be running slower and selecting just about any application or moving from one open screen to another causes the multi-colored wheel of death to raise