Sql syntax inside java

I am having a terrible time with the sql syntax INSIDE a java program. Is there somewhere online that has this information (in easy english!) For example I am trying to insert information in an access table. This is my sql query that works in access. How do I change the syntax to place it into java?
INSERT INTO reservations ( fromcity, tocity, fromdate, todate, air, hotel, rental, airticketamt, hotelamt, rentalamt, customerId )
               VALUES ('Seattle', 'Phoenix', #1/1/2002#, #2/2/2002#, yes, yes, yes, 50, 50, 50, 'CUST001');
I also need to change the actual values (Seattle, etc) to the variables which is also a syntax problem!

Here is a slightly smaller example of building the SQL. I didn't compile this so the syntax may not be 100%, but I think you can figure out the rest from this example.
// Seed the String values for the convenience of the example
String fromCity = "St. Paul";
String toCity   = "Chicago";
String fromDate = "#1/1/2002#";
String toDate   = "#2/2/2002#";
// Build the SQL using the String Values, the trick is to be
// sure you have the appropriate spaces in the SQL when done,
// and that you should use single tick marks to surround String
// values
String sql = "INSERT INTO reservations (fromCity, toCity, fromDate, toDate) " +
                "VALUES ('" + fromCity + "', " +
                         "'"+ toCity   + "', " +
                         "'"+ fromDate + "', " +
                         "'"+ toDate   + "')";
// Take a look at what was generated
// to be sure it is what you want
System.out.println(sql);                                 

Similar Messages

  • SQL code not working inside Java

    Below is my code from java. here, i'm trying to execute below sql code inside my java coding. its preety straight -
    ResultSet rs = null;
    PreparedStatement prepStmt = null;
    String statement="select * from TIMINGTABLE WHERE COUNTRY = 'USA' AND RE_DATE >= TO_DATE('04/11/2012','MM/DD/YYYY') order by COUNTRY";
    prepStmt = con.prepareStatement(statement);
    rs = prepStmt.executeQuery();
    dats it. but, its giving this error ---- SQL syntax error: the token "(" was not expected here
    now, here, when i simply remove this part from the above sql line ----- AND RE_DATE >= TO_DATE('04/11/2012','MM/DD/YYYY') -----the code works perfectly.
    RE_DATE is a date field in the sql table.
    I even tried this option too - TO_DATE(RE_DATE, 'MM/DD/YYYY') >= TO_DATE('04/11/2012','MM/DD/YYYY')
    which is giving same error
    please help
    -prodyut

    927428 wrote:
    Below is my code from java. here, i'm trying to execute below sql code inside my java coding. its preety straight -
    ResultSet rs = null;
    PreparedStatement prepStmt = null;
    String statement="select * from TIMINGTABLE WHERE COUNTRY = 'USA' AND RE_DATE >= TO_DATE('04/11/2012','MM/DD/YYYY') order by COUNTRY";
    prepStmt = con.prepareStatement(statement);
    rs = prepStmt.executeQuery();
    dats it. but, its giving this error ---- SQL syntax error: the token "(" was not expected here
    now, here, when i simply remove this part from the above sql line ----- AND RE_DATE >= TO_DATE('04/11/2012','MM/DD/YYYY') -----the code works perfectly.
    RE_DATE is a date field in the sql table.
    I even tried this option too - TO_DATE(RE_DATE, 'MM/DD/YYYY') >= TO_DATE('04/11/2012','MM/DD/YYYY')
    which is giving same error
    please help
    -prodyutWhat kind of DB you use?
    How do you connect to it?
    (If you use ODBC for example, that won't work)

  • Calling sql dts from java

    I'm able to connect to my sql database and call a stored procedure, but is there any way to call dts?
    here is how i'm accessing the stored procedures:
         Class t = Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
         Connection conn = DriverManager.getConnection (serverURL, user, password);
         CallableStatement procedure = conn.prepareCall( "{ call pushOracle}");
         procedure.execute();I feel like this should be possible, but I can't seem to find the correct syntax.

    I found a solution, but not sure if there are any possible issues this could cause
    Instead of trying to connect to sql and calling the dts I'm using dtsrun inside java to call the dts
    runtime.exec(dtsrun /Samok /U<user> /P<password> /NoraclePush /A tnsNAMES:8=<tnsNames file name> /A sourceDB:8=<SQL DB name> )So I guess the next logical question is, "what are the limitiation or issues that could arise by using the runtime.exec function?"

  • Issue with Oracle.sql.NUMBER in Java Stored Procedure

    When we try to make a call to the Oracle.sql.NUMBER(String) inside a java stored procedure and pass values from '01' to '09', it throws java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    We use Oracle 9.2.0.6 - JServer Release 9.2.0.6.0.
    It works fine for other values. Please find below the code used for simulating the issue outside the application. Thanks.
    create or replace and compile java source named testNumber as
    import oracle.sql.NUMBER;
    import java.sql.SQLException;
    public class TestNumber
           public static String convertNumber(String parm) {
                     NUMBER nTest;
                     try {
                             nTest = new NUMBER(parm);
                             return "TRUE";
                     }catch (SQLException sqle) {
                             return "FALSE";
    create or replace function test_number (p_str in varchar2) return varchar2 as
    language Java name 'TestNumber.convertNumber(java.lang.String) return
    java.lang.String';
    select test_number('05') from dual;  - Throws exception ORA-29532: Java call terminated by uncaught Java exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 3
    select test_number('5') from dual; - Works fine
    select test_number('010') from dual; - Works fine

    Siva,
    I'm only guessing, but it could be an Oracle bug, in which case I suggest checking with Oracle Support.
    (You do have a support contract, don't you? ;-)
    Did you try compiling and running your java class "TestNumber" outside the database?
    Class "oracle.sql.NUMBER" should be in Oracle's JDBC driver, I believe.
    Good Luck,
    Avi.

  • How to convert pl/sql code into java/j2ee

    Hi,
    We have a PL/SQL Oracle App server application that we will support if we can convert in j2ee/java. But when i did take a look at the code, these pl/sql contains all HTML and java code inside the stored procedures.
    And iam looking to explore some tools and mechanisms that can convert these pl/sql in a JAVA application so that i can deploy this new app into my BEA81 environment.
    Does any body has any idea:
    a) How to convert from pl/sql > java ?
    b) Any plugins or tools of BEA that can run these pl/sql (the way thay are currently...i.e w/o converting) in BEA 81 container ?
    thanks, sangita

    these pl/sql contains all HTML and java code insideJava or JavaScript. They are not the same. I wouldn't expect to see Java inside html, whereas JavaScript would be intermixed. On the other hand you might have a java stored proc (Oracle 9/10) which is generating HTML.
    >
    Does any body has any idea:Refactor.
    I doubt it just has html and JavaScript/Java. So what you have is a mess that mixes several things that should have been seperate in the first place.

  • Parse sql syntax

    I have temp table inside my stored procedure:
    CREATE TABLE #tmpOrders(product_id VARCHAR(20))
    SELECT * FROM #tmpOrders o INNER JOIN dbo.products p ON o.productID=p.productID
    o.productID column doesn't exists. The join should be:
    ON o.product_id=p.productID
    But when I create procedure, parser doesn't raise an error. The error is raised at run time.
    Is there some option to check the SQL syntax before run time - to parse also temp table names?
    Thanks,
    Simon

    Hi Simon
    See my latest replay... I create a temporary table and then run CREATE PROCEDURE script to get the error, that was a mistake
    CREATE TABLE #t (c int)
    CREATE PROCEDURE sp1
    AS
    CREATE TABLE #t (c int)
    SELECT * FROM #t JOIN sys.objects o on #t.c1=o.object_id
    Msg 207, Level 16, State 1, Procedure sp1, Line 6
    Invalid column name 'c1'.
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Simple SQL syntax problem

    Ok, I'm sure this is a very simple problem but I'm confused.
    Statement s = con.createStatement();
    s.execute("SELECT COUNT (*) FROM table WHERE id = 6 AND somechar = 'N'");java.sql.SQLException: Syntax error or access violation message from server: "You have an error in y
    our SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax
    to use near '(*) FROM table WHERE id = 6 AND somechar = 'N'' at line 1"
    This works fine when input into the phpMyAdmin database interface. Is there something blatantly wrong with my syntax, or...?

    Maybe it doesn't like the space between COUNT and (*)
    %Yuck.
    Yep, that was it. Thanks.
    Weird, I'm accustomed to programs ignoring most whitespace as long as it doesn't create ambiguity.

  • DB2 SQL syntax

    in Sybase/SQL server, you can do conditional compound SQL like following:
    begin transaction
    begin
    insert into blah values ("blah")
    if(@@rowcount>0)
    begin
    update blah set blah = "blah" where blah = "blah"
    end
    end
    commit transaction;Does anyone know to do that in DB2 SQL syntax?
    Thanks alot.

    Your question has nothing to do with Java, and I don't really understand it.
    If you are talking about Subqueries, then all you need to use is brackets grouping different parts of the statement.

  • Sql syntax

    Can someone kindly tell me the correct syntax for this statement?
    String sql = "UPDATE answers SET q1 = '" + value + "'" + "WHERE EXISTS (SELECT * FROM users u, answers a WHERE u.username = a.username)";
    int numRows = stmt.executeUpdate(sql);
    The error I am getting is:
    Caught SQL Exception: java.sql.SQLException: Syntax error or access violation: You have an error in your SQL syntax near 'EXISTS SELECT * FROM users u, answers a WHERE u.username = a.username' at line 1

    I am using a cookie instead. But, when I use an update, my values are the same for each column, not the appropriate values. Is my syntax below correct?
    String delete = request.getParameter("delete");
    String question = request.getParameter("question");
    String value = request.getParameter("R");
    Cookie[] cookies = request.getCookies();
    if (delete.equals("no") && !value.equals(""))
    if(cookies != null)
    for (int i = 0; i < cookies.length; i++)
    String name = cookies.getName();
    String valuecook = cookies[i].getValue();
    //Cookie getUser = new Cookie(name, valuecook);
    String sql = "UPDATE answers SET q1 ='" + value + "' " + "WHERE USERNAME = '" + valuecook + "'";
    int numRows = stmt.executeUpdate(sql);
    String sql2 = "UPDATE answers SET q2 ='" + value + "' " + "WHERE USERNAME = '" + valuecook + "'";
    int numRows2 = stmt.executeUpdate(sql2);
    String sql3 = "UPDATE answers SET q3 ='" + value + "' " + "WHERE USERNAME = '" + valuecook + "'";
    int numRows3 = stmt.executeUpdate(sql3);
    out.println(value);
    out.println(valuecook);
    // UPDATE table_name SET column_name1 = value1 [, column_name2 = value2, etc.] WHERE criteria
    out.println("Record has been inserted");
    String nextPage = request.getParameter("nextPage");

  • Sql syntax to retrieve xml

    Hi:
    I have a table ASSAYS as:
    ASSAY_NAME VARCHAR2(30)
    ASSAY SYS.XMLTYP(...)
    What is sql syntax to retrieve xml from assay as XMLType object in Java?
    Thanks!

    Get xml from xdb from java

  • Entry-SQL syntax error: CASE not allowed

    Hello All. When I use sap netweaver developer to develop webdynpro applications, I always meet that jdbc error.
    when using inner join,left join, or using case when in the sql, it will pop up Entry-SQL syntax error.
    But I have run the sql in Microsoft SQL Server studio successfully.
    The SQL statement "UPDATE SAPNWDDB.Z_SERIAL SET LASTSERIAL = CASE WHEN ENDWITH IS NOT NULL THEN CASE WHEN LASTSERIAL + 1 > ENDWITH THEN ISNULL(STARTWITH, 0) ELSE LASTSERIAL + 1 END ELSE LASTSERIAL + 1 END WHERE SERIALNO = ?" contains the syntax error[s]: - 1:43 - Entry-SQL syntax error: CASE not allowed
    - 1:78 - Entry-SQL syntax error: CASE not allowed
    - 1:124 - SQL syntax error: the token "(" was not expected here
    Can someone help me? Thank you.

    Hi Arun Jaiswal ,
    Thank you for your answer. But I have tried query in sql editor. Actually it can work. Other than "CASE" syntax, it seems not support inner join and left join in webdynpro either. I even can not query the db views.
    That's imposible jdbc not support these simple syntex. I wonder there is any config control the sql compatibility level.
    I have developped a java programm to test it. It is ok. No error. But the same case pop up error in java webdynpro application.I don't know why.
    I am entry level webdynpro developper.
    Hopefully you can help me.
    Thank you.
    Edited by: zegunlee330 on Sep 3, 2010 4:18 AM

  • Error when making connection:  You have an error in your SQL syntax;

    I'm getting this error when trying to make a simple Database Connection:
    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
    SQLState: 42000
    VendorError: 1064
    I tried a different driver and got the same error with more "?"s in the "use near....." part.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class DBTest{         public static void main(String[] args){                 try{                         Class.forName("com.mysql.jdbc.Driver").newInstance();                 } catch(Exception e){                         System.out.println(e);                         System.exit(0);                 }                 Connection conn = null;                 try {                         conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB?" + "user=root&password=password");                         conn.close();                 } catch (SQLException ex) {                         // handle any errors                         System.out.println("SQLException: " + ex.getMessage());                         System.out.println("SQLState: " + ex.getSQLState());                         System.out.println("VendorError: " + ex.getErrorCode());                 }         } }
    MySQL Server Version:
    Server version: 5.0.67-0ubuntu6 (Ubuntu)

    cotton.m wrote:
    c0c0 wrote:
    I've tried Drivers 5.1 , 5.0 and 3.1 now and I get the same problem every time. I've tried switching databases, users, etc but always get this same error:
    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
    I have the latest version of mysql from the Ubuntu repositories. Do I have to configure that a certain way? It isn't the URL which I supply that it does not like because I've tried multiple URLs and they all give me the same error when I supply the correct information.
    Any help is greatly appreciated.This is.. very odd.
    I have to ask are you really, really sure that your code is just as you posted? Are you sure you aren't running a query of some sort? My guess at this point would be some sort of rather bizarre encoding issue. I'm sorry but I can't reproduce your behaviour, I am connecting to different MySQL instances with no problem from Ubuntu..
    Yes the code is exactly the same as what I posted (except hiding actual usernames and passwords)
    I've even tried to connect to a remote mysql server and get the same behavior (If I type in the wrong database it alerts me there is no db of that name, if I lg in with the wrong password it alerts me cant login ____ @ ______, when I have all the correct information I get that same old error) , I'm somewhat convinced it's my driver now. I thought at first it was the way I had mysql configured but now I think it's my driver or the way I have everything installed. I simply put the driver location in the classpath and do the command:
    export set CLASSPATH=/usr/share/tomcat5.5-webapps/ROOT/lib/mysql-connector-java-5.1.7-bin.jar
    Was this the wrong way to go about doing it? I'm not currently running tomcat I simply put it there because a book said that's where it should go for tomcat, but I wanted to first try this not running tomcat with just a simple normal Java example.

  • SQL Syntax Checker

    Hello,
    I'm curious if there is any tool out there for checking the SQL syntax in the Java program itself. A tool to somehow validate the SQL before sending it thru the JDBC to execute the query on the database.
    If so, can you please refer me to one.
    Thanks

    I think the problem is different DBMS accepts different SQL. Even different version of DBMS.
    There is no way to make sure 100% accurate of SQL.
    The only way to make sure the SQL is accurate to any DBMS is running it and catch it in exception.
    If you SQL is not produced on run time, you can simply check it by the batch utils. For example the sql plus.

  • PL/SQL Object Type - Java oracle.jbo.domain

    PL/SQL Object Type <-> Java oracle.jbo.domain
    can anybody help me, getting my domains to work?
    Following scenario:
    in pl/sql we have an object type called MULTI_LANGUAGE. This type is used for storing multilingual texts as nested table in one(!) column.
    So the object MULTI_LANGUAGE contains a member variable LANGUAGE_COLLECTION of type LANGUAGE_TABLE, which itself is a nested table of objects
    of the type LANGUAGE_FIELD (this again is only a language id and the corresponding content)
    Also the methods setContent(langID, langContent) and getContent(langId) are defined on Object MULTI_LANGUAGE.
    For example: Table having primary key, 2 other columns and one column of object type MULTI_LANGAGE (=nested table of objects)
    |ID|Column1|Column2|  multilingual Column  |
    |--|---------------------------------------|
    |  |       |       |  -------------------  |
    |  |       |       | | 1 | hello         | |
    |  |       |       |  -------------------  |
    |1 | foo   | bar   | | 2 | hallo         | |   <- Row Nr 1
    |  |       |       |  -------------------  |
    |  |       |       | | 3 | ola           | |
    |  |       |       |  -------------------  |
    |--|-------|-------|-----------------------|
    |  |       |       |  -------------------  |
    |  |       |       | | 1 | world         | |
    |  |       |       |  -------------------  |
    |2 | abc   | def   | | 2 | welt          | |   <- Row Nr 2
    |  |       |       |  -------------------  |
    |  |       |       | | 3 | ???  ;-)      | |
    |  |       |       |  -------------------  |
    |--|-------|-------|-----------------------|Now i've tried to modell this structure as an oracle.jbo.domain.
    class MultiLanguage extends Struct having this StructureDef:
    attrs[(0)] = new DomainAttributeDef("LanguageColl", "LANGUAGE_COLL", 0, oracle.jbo.domain.Array.class, 2003, "ARRAY", -127, 0, false, "campusonlinepkg.common.LanguageField");
    and
    class LanguageField extends Struct having this StructureDef:
    attrs[(0)] = new DomainAttributeDef("Id", "ID", 0, oracle.jbo.domain.Number.class, 2, "NUMERIC", -127, 0, false);
    attrs[(1)] = new DomainAttributeDef("Content", "CONTENT", 1, java.lang.String.class, 12, "VARCHAR", -127, 4000, false);
    Is there anything wrong with this StructureDef?
    When running the BC-Browser with -Djbo.debugoutput=console -Djbo.jdbc.driver.verbose=true parameters I get suspect warnings when browsing the records
    [196] Executing FAULT-IN...SELECT NR, NAME FROM B_THESAURI BThesauri WHERE NR=:1
    [197] SQLException: SQLState(null) vendor code(17074)
    [198] java.sql.SQLException: Ungültiges Namensmuster: XMLTEST.null
    ...snip: detail of stack...
    [240] SQLException: SQLState(null) vendor code(17060)
    [241] java.sql.SQLException: Deskriptor konnte nicht erstellt werden: Unable to resolve type "null"
    ...snip: detail of stack...
    [280] Warning:No element type set on this array. Assuming java.lang.Object.
    (XMLTEST is the name of the schema)
    Seems as if the framework can't read the TypeDescriptor or does not know which descriptor to read (XMLTEST.null??)
    Do I have to implement my own JboTypeMap?
    Please help, I'm stuck.
    Thanks in advance, Christian

    Thanks for your suggestion, but it seems to me as if there is one level missing.
    in pl/sql I have following structure:
    Struct MULTI_LANGUAGE (Object type) - outermost
      Array LANGUAGE_TABLE (nested table type)
        Struct LANGUAGE_FIELD (Object type simple) - innermostthe reason why i had to wrap another struct around the array was because it is not possible to define methods on a nested table. this is only possible on objects.
    on the outermost object type (which holds the array of language fields) I needed to define following 2 methods for direct access:
    getContent (langId in number) returns varchar2
    setContent (langId in number, langContent in varchar2)
    I would like to rebuild the same structure in java, because newly written java code should live in perfect harmony with legacy pl/sql code ;-)
    Both applications (Java and pl/sql) have to access the same data as long as migration to java goes on.
    Is this nested structure too much for a Domain?
    Any other suggestions?
    Thanks again, Christian

  • How i connect to SQL server using java?

    hi every body
    i need to connect to a sql server database using java
    i do not know sql driver in java
    plz help me
    thanks

    This is certainly the wrong forum for that question. Search in the JDBC forum. This has been asked and answered many times.

Maybe you are looking for