Unclosed character literal

I am getting the following error message, I am certain that I am putting an incorrect character in here somewhere. Any ideas?
[javac]
C:\tomcat\work\Standalone\localhost\hd\Report_SystemListByImplFeatures_jsp.java:53: unclosed character literal
[javac] (features.indexOf('ov')) >= 0)?"1":"0",

Single quotes should only be used to enclose a single unescaped character, or an escape sequence that represent a single character. If you intend to search for the substring "ov" then you must enclose ov in double quotes.

Similar Messages

  • Unclosed string literal

    I am having a problem compliling the below:
    public class Name
    public static void main (String[] args)
    char name,bday,hobby,book,movie;
    name = 'Brian ';
    bday = 'March 15th 1975';
    hobby = 'Video Games';
    book = '\"Lord of the Rings\"';
    movie = '\"Star Wars\"';
    System.out.println ("My name is:" + name);
    System.out.println ("I was born on:" + bday);
    System.out.println ("My hobbies include:" +hobby);
    System.out.println ("My foavorite book is:" + book);
    System.out.println ("Also, my favorite movie of all time is:" + movie);
    I keep getting unclosed string literal errors but I am closing them off w/ a ' not a " as I thought the char primative should be handled. Any help for someone starting out would be appreciated.
    Thanks

    A character can only hold one character.
    Brian, for example, is more than one letter, and therefore more than one character. Therefore, 'Brian' is not a valid character. "Brian" is, however, a valid String.
    In other words, change all your char variables to Strings.

  • Unclosed character class near index 0

    Hi foks,
    I am tryin to remove few characters from a string with the help of replaceAll ( String, String ) method.
    But at the first replacement itself it gives error "Unclosed character class near index 0".
    what does this error mean? I dont have any ' [ ' character in that string. It used to be there, but now I am removing all the occuring of the ' [ ' char right at the creation of string.
    Thanks in advance.

    Hi,
    Here is the code.
    [ CODE ]
    public static String extract(String para)
    String definition = para.substring(para.indexOf("<ol>"),para.indexOf("</ol>"));
    StringBuffer meanings=new StringBuffer();
    StringReader reader = new StringReader(definition);
    StringWriter writer = new StringWriter();
    boolean append=false;
    int ch;
    try
    while((ch=reader.read()) != -1)
    if(ch=='<' || ch=='&')
    append = false;
    continue;
    else if(ch=='>' || ch==';')
    append = true;
    continue;
    if(append && ch != '[' && ch != ']')
    writer.write(ch);
    catch(IOException e)
    System.out.println("IOException:"+e.getMessage());
    catch(Exception e)
    System.out.println("IOException:"+e.getMessage());
    meanings=writer.getBuffer();
    String temp = meanings.toString();
    System.out.println("temp:"+temp);
    temp=temp.replaceAll("["," ");
    System.out.println("temp:"+temp);
    temp=temp.replaceAll(" "," ");
    System.out.println("temp:"+temp);
    return temp;
    [ /CODE ]

  • PatternSyntaxException: Unclosed character class near index

    Hi,
    I want to replace in a string a expression like "^1:2" by "^(1/2)":
    For example, "V/Hz^1:2" would be converted to "V/Hz^(1/2)".
    I tried the following code:
    String oldExponent = "[^](\\d+):(\\d+)"; // e.g. ^1:2
    String newExponent = "^($1/$2)";         // e.g. ^(1/2)
    myString = myString.replaceAll(oldExponent, newExponent);but the following exception is thrown in the third line:
    java.util.regex.PatternSyntaxException: Unclosed character class near index 13
    [^](\d+):(\d+)
                 ^Any idea?
    Thanks in advance.

    Thank you, jverd, you are pretty right.
    Now I tried with
    "\\^(\\d+):(\\d+)"and it works.
    I tried to avoid ^ being interpreted as the beginning of the line, and didn't realize the interpretation inside the brackets.
    Escaping this character works well.

  • Character literal

    We can also use the escape sequence \ddd to specify a character literal by octal value, where each digit d can be any octal digit (0?7), as shown in Table 2.8. The number of digits must be three or fewer, and the octal value cannot exceed \377, that is, only the first 256 characters can be specified with this notation.

    okay, so what's your question?

  • Pass UTF character literal from Windows command prompt

    I'm trying to pass \u00fd (� - 0253) via the windows command line as a parameter to a java app. "DOS" is converting it to a superscripted 2. Any ideas on how to work around this? It works fine if I pass the parameter via a windows program.
    Thanks

    \00fd is "Latin Small Letter Y With Acute" according to my Unicode crib. But your DOS window doesn't use Unicode, it uses CP437 or CP850 depending on where in the world it thinks you live. (Both of them have the superscript-2 character at the FD code point.) I don't see the y-acute character anywhere in CP437, so if you're in North America (or maybe Britain too?) you can't do that. In CP850 the EC (decimal 236) code point is y-acute.
    However you aren't out of luck in either case. There is a DOS command "chcp". If you type "chcp" at the command line it tells you what your code page is. If you type "chcp 850" at the command line it will change your code page to CP850, if it can.
    (I am getting all this information from my MS-DOS 5.0 User's Guide and Reference, by the way. I may put it up for sale on eBay.)

  • I keep an error, which say unclosed string literal

    String sqlStatement=("INSERT INTO Customer(Customer_name, Address1, Address2, DayPhone, MobilePhone, AccountNumber, Email, Sort_code, Username, Password)
    VALUES ("+s1+","+s2+","+s3+","+s4+","+s5+","+s6+","+s7+","+s8+","+s9+","+s10+")");
    can anyone help!

    Zadok, whats the difference, thanks for the responseLook closely:
    the first "+ should not be there.
    Either way, instead of removing it, I highly, highly recommend you use a PreparedStatement instead.

  • Specifying ' character in an array of characters

    How do I edit my code so that I can include the ' character in my list of characters without getting the error below?
    (The character referred to is delim[12] in my array)
    blazes > javac Words.java
    Words.java:44: empty character literal
    delim[12] = ''';
    ^
    Words.java:44: empty character literal
    delim[12] = ''';
    ^
    Words.java:44: unclosed character literal
    delim[12] = ''';
    ^
    char [] delim = new char[13];
    delim[0] = ',';
    delim[1] = '.';
    delim[2] = '?';
    delim[3] = '!';
    delim[4] = '-';
    delim[5] = '_';
    delim[6] = ';';
    delim[7] = ':';
    delim[8] = '"';
    delim[9] = '`';
    delim[10] = '�';
    delim[11] = '�';
    delim[12] = ''';
    Thank you

    The object of my program is to read in a text file and output a new text file with each word and puncutation mark of the file on a separate line. I can also use a String Tokenizer, however if I include the " character in my list of delimeters for the Tokenizer like this:
    StringTokenizer st = new StringTokenizer(line, ",��"`.?!-_;': ", true);
    I get the error:
    TaggerFile.java:31: illegal character: \96
    StringTokenizer st = new StringTokenizer(line, ",??"`.?!-_;': ", true);
    ^
    TaggerFile.java:31: unclosed character literal
    StringTokenizer st = new StringTokenizer(line, ",??"`.?!-_;': ", true);
    ^
    TaggerFile.java:31: unclosed string literal
    StringTokenizer st = new StringTokenizer(line, ",??"`.?!-_;': ", true);
    ^
    TaggerFile.java:45: ';' expected
    So how do I specify that I want my program to tokenize the file with every possible delimeter?!
    , � � " ` . ? ! - _ ; ' :

  • Unicode literal for '\' (Backslash)

    Hi there!
    I've got a problem with the Java compiler. I think he is cheating me!
    Just the simple command:
    System.out.println('\u005c');
    causes the error:
    Import.java:171: unclosed character literal
    System.out.println('\u005c');
    ^
    The unicode character 005c is the backslash, and the backslash itself is the start to any escape sequence.
    But isnt it possible to express the '\' as a unicode escape sequence?!?
    Is this a bug of the compiler?
    Greetings Maik

    You are expressing \u005c as an escape, just don't realize it...
    The compiler read your println statement and converted the '\u005c' to '\'. This illegal character (see below) terminated reading of the line. As a result, the compiler didn't see the trailing single quote and the trailing parenthesis.
    Since it had read the first single quote, but not the second, it issued the error "unclosed character literal".
    You should have also received an error "')' expected" for the same reason. Did you?
    (3.10.4 Character Literals, The Java Language Specification, notes that single character literals of '\' are not legal and will result in a compile-time error, as it did above.)

  • Problem with the "\" character.

    Hello
    Why I can not compile the folowing source (very short) :
    public class Test4 {
    char tmp = '\u005C';
    public static void main(String args[]){
    the error is :
    src/Test4.java:2: unclosed character literal
    char tmp = '\u005C';
    ^
    1 error
    The problem is the same with javac and jikes.
    FYI, the 005C is the "\" character. If I use an other one, no problem, I can compile and run the .class file.
    Anyone can help me ?
    Best regards from Bordeaux, France.
    K96

    ok, you're right. But, my problem is a little bit different :
    I would like to replace the "\n" character (new line) by the 2 characters "\n".
    I test this source code :
    String tmp = "First line\nSecond line";
    tmp.replaceAll("\n", "\u005C\u005Cn");
    System.out.println(tmp);
    tmp.replaceAll("\n", "\\n");
    System.out.println(tmp);
    tmp.replaceAll("\n", "\\\\n");
    System.out.println(tmp);
    The 3 results are the same :
    First line
    Second line
    I never have "First line\nSecond line".
    Best regards.
    K96
    PS : The objective is to write the string in a SQL request.

  • Using textboxes in insert command

    Sir,
    I had a doubt about insert command while I was trying to give the content of the swing text boxes as the arguments to the insert command.Is it possible?.How can i give values to the fields of a table through GUI components.

    Hi,
    I meant using text boxes in insert statement.because all time we should not give literals.we should have got inputs from swing panel from which we have to
    insert data into tables.So I asked how can i give variables or input GUI Components as arguments of insert statement. Also I gave the code below
    //CRM Sections Campaign
    //package marketing;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class CRM_Marketing_1B extends JFrame implements ActionListener
    JOptionPane joptMessage;
    JButton jbtnSave;
    JButton jbtnClear;
    JButton jbtnExit=new JButton("Exit");
    public CRM_Marketing_1B(String title)
    Container conMarketingPane=getContentPane();
    conMarketingPane.setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel lblCustomer_Id=new JLabel("Customer ID");
    JLabel lblCustomer_Name=new JLabel("Customer Name");
    JLabel lblCompany_Name=new JLabel("Company Name");
    JLabel lblDesignation=new JLabel("Designation");
    JLabel lblAddress1=new JLabel("Address1");
    JLabel lblAddress2=new JLabel("Address2");
    JLabel lblQuantity=new JLabel("Quantity");
    JLabel lblUnit_Price=new JLabel("Unit Price");
    JLabel lblInterest_Level=new JLabel("Interest Level");
    JLabel lblContact_No=new JLabel("Contact No");
    JLabel lblMobile_No=new JLabel("Mobile No");
    JLabel lblEmail=new JLabel("Email Address");
    JLabel lblEmployee_Id=new JLabel("Employee ID");
    JLabel lblCampaign_Date=new JLabel("Campaign Date");
    JLabel lblNext_Appointment=new JLabel("Next Appointment");
    JLabel lblCampaign_Id=new JLabel("Campaign ID");
    JLabel lblTeam_Id=new JLabel("Team ID");
    JLabel lblOrder_No=new JLabel("Order No");
    JLabel lblResult=new JLabel("Result");
    JTextField txfCustomer_Id=new JTextField(30);
    JTextField txfCustomer_Name=new JTextField(30);
    JTextField txfCompany_Name=new JTextField(30);
    JTextField txfDesignation=new JTextField(30);
    JTextField txfAddress1=new JTextField(30);
    JTextField txfAddress2=new JTextField(30);
    JTextField txfQuantity=new JTextField(30);
    JTextField txfUnit_Price=new JTextField(30);
    JTextField txfInterest_Level=new JTextField(30);
    JTextField txfContact_No=new JTextField(30);
    JTextField txfMobile_No=new JTextField(30);
    JTextField txfEmail=new JTextField(30);
    JTextField txfEmployee_Id=new JTextField(30);
    JTextField txfCampaign_Date=new JTextField(30);
    JTextField txfNext_Appointment=new JTextField(30);
    JTextField txfCampaign_Id=new JTextField(30);
    JTextField txfTeam_Id=new JTextField(30);
    JTextField txfOrder_No=new JTextField(30);
    JTextField txfResult=new JTextField(30);
    JButton jbtnSave=new JButton("Save");
    JButton jbtnClear=new JButton("Clear");
    JButton jbtnExit=new JButton("Exit");
    conMarketingPane.add(lblCustomer_Id);
    conMarketingPane.add(lblCustomer_Name);
    conMarketingPane.add(lblCompany_Name);
    conMarketingPane.add(lblDesignation);
    conMarketingPane.add(lblAddress1);
    conMarketingPane.add(lblAddress2);
    conMarketingPane.add(lblQuantity);
    conMarketingPane.add(lblUnit_Price);
    conMarketingPane.add(lblInterest_Level);
    conMarketingPane.add(lblContact_No);
    conMarketingPane.add(lblMobile_No);
    conMarketingPane.add(lblEmail);
    conMarketingPane.add(lblEmployee_Id);
    conMarketingPane.add(lblCampaign_Date);
    conMarketingPane.add(lblNext_Appointment);
    conMarketingPane.add(lblCampaign_Id);
    conMarketingPane.add(lblTeam_Id);
    conMarketingPane.add(lblOrder_No);
    conMarketingPane.add(lblResult);
    conMarketingPane.add(txfCustomer_Id);
    conMarketingPane.add(txfCustomer_Name);
    conMarketingPane.add(txfCompany_Name);
    conMarketingPane.add(txfDesignation);
    conMarketingPane.add(txfAddress1);
    conMarketingPane.add(txfAddress2);
    conMarketingPane.add(txfQuantity);
    conMarketingPane.add(txfUnit_Price);
    conMarketingPane.add(txfInterest_Level);
    conMarketingPane.add(txfContact_No);
    conMarketingPane.add(txfMobile_No);
    conMarketingPane.add(txfEmail);
    conMarketingPane.add(txfEmployee_Id);
    conMarketingPane.add(txfCampaign_Date);
    conMarketingPane.add(txfNext_Appointment);
    conMarketingPane.add(txfCampaign_Id);
    conMarketingPane.add(txfTeam_Id);
    conMarketingPane.add(txfOrder_No);
    conMarketingPane.add(txfResult);
    conMarketingPane.add(jbtnSave);
    conMarketingPane.add(jbtnClear);
    conMarketingPane.add(jbtnExit);
    setSize(900,900);
    setVisible(true);
    lblCustomer_Id.setLocation(50,50);
    lblCustomer_Name.setLocation(50,70);
    lblCompany_Name.setLocation(50,90);
    lblDesignation.setLocation(50,110);
    lblAddress1.setLocation(50,130);
    lblAddress2.setLocation(50,150);
    lblQuantity.setLocation(50,170);
    lblUnit_Price.setLocation(50,190);
    lblInterest_Level.setLocation(50,210);
    lblContact_No.setLocation(50,230);
    lblMobile_No.setLocation(50,250);
    lblEmail.setLocation(50,270);
    lblEmployee_Id.setLocation(50,290);
    lblCampaign_Date.setLocation(50,310);
    lblNext_Appointment.setLocation(50,330);
    lblCampaign_Id.setLocation(50,350);
    lblTeam_Id.setLocation(50,370);
    lblOrder_No.setLocation(50,390);
    lblResult.setLocation(50,410);
    txfCustomer_Id.setLocation(250,50);
    txfCustomer_Name.setLocation(250,70);
    txfCompany_Name.setLocation(250,90);
    txfDesignation.setLocation(250,110);
    txfAddress1.setLocation(250,130);
    txfAddress2.setLocation(250,150);
    txfQuantity.setLocation(250,170);
    txfUnit_Price.setLocation(250,190);
    txfInterest_Level.setLocation(250,210);
    txfContact_No.setLocation(250,230);
    txfMobile_No.setLocation(250,250);
    txfEmail.setLocation(250,270);
    txfEmployee_Id.setLocation(250,290);
    txfCampaign_Date.setLocation(250,310);
    txfNext_Appointment.setLocation(250,330);
    txfCampaign_Id.setLocation(250,350);
    txfTeam_Id.setLocation(250,370);
    txfOrder_No.setLocation(250,390);
    txfResult.setLocation(250,410);
    jbtnSave.setLocation(250,450);
    jbtnClear.setLocation(350,450);
    jbtnExit.setLocation(450,450);
    txfCustomer_Id.setRequestFocusEnabled(true);
    txfCustomer_Id.requestFocus();
    jbtnSave.addActionListener(this);
    jbtnClear.addActionListener(this);
    jbtnExit.addActionListener(this);
    public void actionPerformed(ActionEvent ae)
    if(ae.getSource().equals(jbtnSave))
    //' &txfAddress1& ',' &txfAddress2& ',' &txfQuantity& ',
    //' &txfUnit_Price& ',' &txfInterest_Level& ',' &txfContact_No& ',
    //' &txfMobile_No& ',' &txfEmail& ',' &txfEmployee_Id& ',' &txfCampaign_Date& ',
    //' &txfNext_Appointment& ',' &txfCampaign_Id& ',' &txfTeam_Id& ',' &txfOrder_No& ',' &txfResult& '
    try
    Class.forName("jdbc.odbc.JdbcOdbcDriver");
    Connection connCampaign=DriverManager.getConnection("jdbc:odbc:CRMSource");
    Statement stmtCampaign=connCampaign.createStatement();
    /* stmt.executeUpdate("insert into Campaign values('" &jtxfCustomer_ID& "',&jtxfCustomer_Name&,
    ' &jtxfCustomer_ID& ',' &txfCompany_Name& ',' &txfDesignation& ',' &txfAddress1& ',' &txfAddress2& ',
    ' &txfQuantity& ',' &txfUnit_Price& ',' &txfInterest_Level& ',' &txfContact_No& ',
    ' &txfMobile_No& ',' &txfEmail& ',' &txfEmployee_Id& ',' &txfCampaign_Date& ',
    ' &txfNext_Appointment& ',' &txfCampaign_Id& ',' &txfTeam_Id& ',' &txfOrder_No& ',' &txfResult& ')");*/
    JOptionPane.showMessageDialog(this,"Statement was saved");
    catch(Exception ex)
    ex.printStackTrace();
    I got "unclosed character literal" error when i tried to execute the above java source file .
    help me to get the required result.

  • Sql in jsp

    can n e 1 tell me where i am going wrong i am trying to use sql in a jsp to try to take out specific tuples from a table in my db but it is not working. i have been looking at the code for ages and can't figure out where i'm going wrong. please help!!!!!!!!!!!
    here is the code and the errors.
    <%@ page import="java.sql.*, java.util.*, java.io.* " %>
    <body bgcolor="#ffffcc">
    <% String name = (String)session.getAttribute("thefname"); %>
    <% String staffid = (String)session.getAttribute("theusername"); %>
    <center>
    <h2><tt> Here are the assignments you've marked :<%=name%>:<%=staffid%> </tt></h2>
    <%
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         java.sql.Connection con1 = null;
         Statement stmt1 = null;
         ResultSet rs1 = null;
         String queryStr1 = null;
    try{
    con1 = DriverManager.getConnection(
              "jdbc:mysql://bushmouth.doc.stu.mmu.ac.uk:3306/dutts?user=*****&password=*********");
    stmt1 = con1.createStatement();
    queryStr1 = "SELECT *
                   FROM e modresults, d module
                   WHERE e.modid = d.modid
                   And d.staffid = '" + staffid + "'";
    rs1 = stmt1.executeQuery(queryStr1);
    %>
    <center>
    <H2 color="#99ffff"><tt> All submited assignments</tt></h2>
    <hr>
    <br>
    <table border="1" bgcolor="#66ccff" >
    <tr>
    <th> modid</th>
    <th>courseid</th>
    <th>studentid</th>
    <th> assessmentno</th>
    <th> url</th>
    <th> grade</th>
    <th>tutorcomment </th>
    </tr>
    <%
         while (rs1.next())
              String modid = rs1.getString(1);
                   String courseid = rs1.getString(2);
                   String studentid = rs1.getString(3);
                   String assessmentno = rs1.getString(4);
                   String url = rs1.getString(5);
                   String grade = rs1.getString(6);
    String tutorcomment = rs1.getString(7);
    %>
    <tr><td><%=modid%></td>
    <td><%=courseid%></td>
    <td><%=studentid%></td>
    <td><%=assessmentno%></td>
    <td><a href="<%=url%>"><%=url%></a></td>
    <td><%=grade%></td>
    <td><%=tutorcomment%></td></tr>
    </center>
    <%
         } // end while()
    }catch(SQLException s){%> <%= s%> <% }
    finally{
    // clean up.
         try{
              if (rs1!=null) rs1.close();
              if (stmt1!=null) stmt1.close();
              if (con1!=null) con1.close();
         }catch(SQLException s){}
    %>
    </TABLE>
    <br>
    <button style="width:200;height:45"
    onClick="history.go(-1)"><b>back to account</b></button>
    </body>
    </center>
    </body>
    rg.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 16 in the jsp file: /jsp/vmarked.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    C:\tomcat\work\Standalone\localhost\student_mod2_dutts\jsp\vmarked_jsp.java:74: unclosed string literal
    queryStr1 = "SELECT *
    ^
    An error occurred at line: 16 in the jsp file: /jsp/vmarked.jsp
    Generated servlet error:
    C:\tomcat\work\Standalone\localhost\student_mod2_dutts\jsp\vmarked_jsp.java:77: unclosed character literal
                   And d.staffid = '" + staffid + "'";
    ^
    2 errors

    thanks for that guys it has sorted that out. but i still have 1 little problem with it. i am getting the following error when i try to use that sql command
    java.sql.SQLException: General error: Table 'dutts.e' doesn't exist
    i know it's not really a java problem , but can i be cheeky enough to ask if some one could see if i have written my sql statement correctly?
    here is the statement i have written
    queryStr1 = "SELECT * FROM e modresults, d module WHERE e.modid = d.modid And d.staffid = '" + staffid + "'";

  • UNICODE characters in JAVA

    i have a doubt about the following codes
    public class Attempt
    // char a='\u000A';
    this code is not compiling even i the line is commented in the code.
    it gives the following compile time error:
    ---------- javac ----------
    D:\saurabh\Attempt.java:4: unclosed character literal
    ^
    D:\saurabh\Attempt.java:4: <identifier> expected
    ^
    2 errors
    Normal Termination
    Output completed (1 sec consumed).
    IS this a bug in JAVA
    plz reply to this
    rajeev

    This happens because the unicode literals are translated prior to compilation;
    \u000a is the LF character, so what you actually get the compiler trying to
    handle is:
    char c = '    // the unicode has been replaced by the character it represents
    ';or something similar.
    It might have been nicer if these literals were preserved during compilation and
    substituted at run time, but that would probably cause all kinds of other
    technical problems.

  • Adding parentheses to each item in HashSet

    Dear All,
    Having almost completed my first java tool which queries a database to allow user-defined filtering, I'm running into a last 'small' problem:
    I won't bore you guys with the whole thing, but instead will just focus on the part where i'm stuck, in the hope that somebody can give me a useful tip as to how to solve this! Thanks very much in advance for any input!
    Basically, what it comes down to is that I query the database twice, resulting in two lists of data stored as HashSets in Java, to then work out the intersect of them both with the listI.retainAll(listII) function. Finally, I want to use the merged list to query the database again, using the variables listed in the final set. In order to use the list in the query, I first convert the HashSet to a string as follows:
    String convList = listI.toString();As this results in a string with square brackets [] and mySQL needs regular brackets, I convert them like this:
    convList = convList.replace('[', '(');
    convList = convList.replace(']', ')');This will result in something along the lines as (result1, result2, result3, result4, etc.). The problem is though, that I would need it to be like
    ("result1", "result2", "result3", "result4") in order for mySQL to accept it using the IN clause.
    I tried to add the parentheses using:
    convList = convList.replaceAll(',', '",');
            convList = convList.replaceAll(' ', ' "');but the Java compiler complains of an error with "unclosed character literal", so I was hoping somebody could maybe give me a hint as to how I can add parentheses for each member in the list? Thanks alot in advance

    les_paulde wrote:
    wow, thanks for your swift reply! This definitely solved my problem and I can now run the query. The code turned out as follows:
    String convList = listI.toString();
    convList = convList.replace("[", "(\"");
    convList = convList.replace("]", "\")");
    convList = convList.replaceAll(",", "\",");
    convList = convList.replaceAll(" ", " \"");
    And what happens if the String representation of the object in your list contains one of the characters you're replacing? It will go awfully wrong!
    This is safer:
    public static String asString(List<?> list) {
        StringBuilder b = new StringBuilder();
        b.append('(');
        for(int i = 0; i < list.size(); i++) {
            b.append('"').append(list.get(i)).append('"');
            if(i < list.size()-1) b.append(", ");
        return b.append(')').toString();
    System.out.println(asString(listI));

  • JDBC  Inner Query Code Needed

    Hi
    I have a table called Sale
    contains a column called quantity_Available_For_Sale numeric(18,0)
    Another table called Withdrawal_Operations contains a column called quantity_withdrawan numeric(18,0)
    I need a jdbc code that add quantity_withdrawan value when inserted in the Withdrawal_Operations to the sum of the values of quantity_Available_for_Sale field
    this is my trial code
      String sql= "update Sale  set  Item_code ='"+jTextField7.getText()+"',quantity_Available_for_Sale='"+jTextField10.getText()+"SELECT SUM"+""+quantity_Available_for_Sale+""+" FROM "+'Sale'+"+"'WHERE  withdrawal_id='"+jTextField12.getText()+"'";It generates two errors
    unclosed character literal.
    not a statement.
    thanks
    Edited by: VANPERSIE on May 7, 2011 10:50 PM

    Hi,
    This is what you currently have, I think. All I have done is some formatting in order to be able to read it.
    String sql = "update Sale set  Item_code ='"   +
                 jTextField7.getText()             +
                 "',quantity_Available_for_Sale='" +
                 jTextField10.getText()            +
                 "'SELECT SUM'"                    +
                 ""                                +
                 "("                               +
                 quantity_Available_for_Sale       +
                 ")"                               +
                 ""                                +
                 " FROM "                          +
                 Sale                              +
                 ""                                +
                 "' WHERE  withdrawal_id='"        +
                 jTextField12.getText()            +
    Statement stmt = con.createStatement(sql);That approach is wrong for several reasons, some being
    1. Each time you concatenate a string together, it will be a brand new SQL statement for the server to hard parse.
    Not only is this inefficiant, it breaks your SQL cache, causes latching which is definite resource.
    Always use bind variables when dealing with databases.
    2. You are subject to SQL injection. If your text fields contains SQL or parts of SQL, malicious users could take advantage of that.
    3. Your statement is not type safe, and you need to clutter up with single quotes to turn strings into literals.
    With this kind of code you are at sub-zero level of writing database applications.
    A better approach would be to use PreparedStatement as suggested.
    In your case something like:
    String sql = "update Sale set  Item_code =?"   +
                 ",quantity_Available_for_Sale="   +
                 "SELECT SUM"                      +
                 ""                                +
                 "("                               +
                 quantity_Available_for_Sale       +
                 ")"                               +
                 ""                                +
                 " FROM "                          +
                 Sale                              +
                 ""                                +
                 " WHERE  withdrawal_id=?";
    PreparedStatement pstmt = con.prepareStatement(sql);
    pstmt.setString(1, jTextField10.getText());
    pstmt.setString(2, jTextField12.getText());This should take of the three points listed above.
    In my opinion you are now at level 1 of writing database applications.
    You still have some problems. Above sql, is not SQL, it is nothing but a Java String.
    You will struggle to make it into valid SQL, probably by using a cumbersome trial and error process.
    And this is even quite simple SQL.
    In your case you seem to be pulling data from the front end, and use this directly in the data access layer.
    So, you have no POJO layer (I am not saying that you should have).
    This makes the SQL a perfect candidate for what you already mentioned yourself, stored procedures.
    Using a stored procedure, you have something like this:
    String sql = "{call sales_pck.set_quant_avail(?,?)}";
    CallableStatement cstmt = con.prepareCall(sql);
    cstmt.setString(1, jTextField10.getText());
    cstmt.setString(2, jTextField12.getText());Looks much more appealing doesn't it?
    - And not much room for SQL syntax errors.
    You will of course have to implement that stored procedure. Something many Java developers do not like to do.
    Don't know why - to me it smells like technology anxiety.
    There is nothing wrong about stored procedures, and nothing old school about them. In your case it even seems like a sensible thing to do.
    The first advantage about it, is that you will get to work in a layer (The database) that actually knows SQL.
    Here's an attempt to implement your stored, implmented by using a PL/SQL package:
    create or replace package sales_pck as
      procedure set_quant_aval (
        p_item_code        in sale.item_code%type,
        p_with_drawal_id   in sale.withdrawal_id%type
    end sales_pck;
    create or replace package body sales_pck as
      procedure set_quant_aval (
        p_item_code        in sale.item_code%type,
        p_with_drawal_id   in sale.withdrawal_id%type
      ) is
      begin
        update sale
        set    item_code = p_item_code,
               quantity_available =
               select sum (quantity_available_for_sale)
                  from   sale
               where  withdrawal_id = p_with_drawal_id;
      end set_quant_aval;
    end sales_pck;
    /Doing this, you will soon realize that you are not quite there.
    You SQL is syntactically wrong (At least in Oracle).
    But you are now in the right environment to fix it.
    It is probably also semantically wrong, it gives little meaning, and you are probably facing mutating table
    (At least in Oracle and other databases supporting read consistency)
    Note on syntax errors. You probably mean
        update sale
        set    item_code = p_item_code,
               quantity_available =
                 (select sum (quantity_available_for_sale)
                  from   sale
                  where  withdrawal_id = p_with_drawal_id);Or
        update sale
        set    item_code = p_item_code,
               quantity_available =
                 (select sum (quantity_available_for_sale)
                  from   sale)
        where  withdrawal_id = p_with_drawal_id;I can't say which, they seem equally wrong.
    This is what you should do:
    1. Write a correct update statment in a query tool of your choice.
    2. Put that statment inside a stored procedure
    3. Test that procedure from a query tool
    4. Implement the procedure call in your application
    5. Test it.
    Conclusion:
    If you intend to do any (handwritten) SQL in your application, the goal is:
    - write as little as you can in the Java layer
    - write as much as possible in the database layer
    One way of achieving this, is by utilizing stored procedures.
    Regards
    Peter

Maybe you are looking for