Problem: JSP, MySQL, UTF-8

Hello!
I use Netbeans 6.5, MySQL 5.0.67, Apache Tomcat 6.0.18, MySQL Connector J 5.1.6 to write simple web database application in JSP. Now I have problem with encoding of non-latin character strings returned from database.
Database was created by query:
CREATE DATABASE mydb DEFAULT CHARACTER SET = utf8Resource was defined in context.xml as follows:
    <Resource name="jdbc/ipdbDatasource"
        auth="Container"
        type="javax.sql.DataSource"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/ipdb_10?autoReconnect=true&characterSetResults=UTF-8"
        username="root"
        password=""
        maxActive="100"
        maxIdle="30"
        maxWait="10000"/>Test page source is:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<sql:query var="rooms" dataSource="jdbc/ipdbDatasource" >
    SELECT address, descr FROM room
</sql:query>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>&#1058;&#1077;&#1089;&#1090;&#1086;&#1074;&#1072;&#1103; &#1089;&#1090;&#1088;&#1072;&#1085;&#1080;&#1094;&#1072;</h1>
        <c:forEach var="room" items="${rooms.rows}">
            <p>${room.address}</p>
        </c:forEach>
    </body>
</html>Page header <h1> content is OK, but ${room.address} appears in wrong encoding. What can cause this problem?

I would suggest that you start by looking a jdbc only. JSP is not JDBC. XML is not JDBC.
Moreover the ONLY way to determine what is actually being extracted from the database in a text value is to print the characters as integers. If you attempt to display them using ANYTHING (System.out, swing, xml, file io) then they will be mapped. And mapped data is not the same as what you got from the database.

Similar Messages

  • Handshaking Problem ( JSP & MySql )

    Dear All
    I am facing the foolowing problem with mysql and servlet:
    exception
    javax.servlet.ServletException: Communication failure during handshake. Is there a server running on localhost:3306?
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
         org.apache.jsp.jobcard16_jsp._jspService(org.apache.jsp.jobcard16_jsp:1599)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.sql.SQLException: Communication failure during handshake. Is there a server running on localhost:3306?
         com.mysql.jdbc.MysqlIO.init(MysqlIO.java:619)
         com.mysql.jdbc.Connection.createNewIO(Connection.java:1605)
         com.mysql.jdbc.Connection.connectionInit(Connection.java:1056)
         com.mysql.jdbc.Driver.connect(Driver.java:297)
         java.sql.DriverManager.getConnection(Unknown Source)
         java.sql.DriverManager.getConnection(Unknown Source)
         org.apache.jsp.jobcard16_jsp._jspService(org.apache.jsp.jobcard16_jsp:88)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

    nikhil_p_chavan wrote:
    Yes, there is MySql running on 3306.The exception says it is not. This can have the following (logical) causes:
    1) MySQL is actually not running on 3306.
    2) MySQL does not allow connections.
    3) Some firewall software is blocking MySQL.
    4) Some firewall software is blocking port 3306.
    And in the future please don't mark the topic as answered while your actual problem is not solved. I was under the impression that it was answered right after my first reply and when you confirmed that there was no MySQL server at post 3306.

  • JSP + MYSQL question: input form value into a SQL table

    Hello,
    I am writing some JSP code to read input information from a input form to write this information into a SQL field.
    My problems are:
    - how can i pass the input form information to other jsp file ? (like Getproperty of something like this)
    - how can i move the content of any input information into a variable ? I mean something like this:
    String a1;
    username.value.of.the.input.field.in.forum_jsp = a1.in.addmessage_jsp;and then:
    int rowsAffected = stmt.executeUpdate("INSERT INTO forummessages (messagecode, " +  " usercode, " + " messagedate,  " + " message) VALUES(6,3,06/07/2007,'" + a1 + "')");------
    The SQL table looks like this:
    stmt.executeUpdate("CREATE TABLE forummessages (messagecode int AUTO_INCREMENT PRIMARY KEY, usercode int, messagedate date, message char(255) not null)");My codes are:
    forum.jsp - this one should pass the input information to addmessage.jsp
    <%@ page contentType="text/html; charset=iso-8859-2" %>
    <%@ page import="java.sql.*" %>
    <%
    Connection con = null;
    Statement stmt = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      String url =  "jdbc:mysql://localhost:3306/mysql";
      con =  DriverManager.getConnection(url,"root", "");
      stmt = con.createStatement();
      String sql = "SELECT * FROM forummessages,users,bmwecode WHERE (forummessages.usercode=users.usercode) AND (users.bmwcode=bmwecode.bmwcode)";
      ResultSet rs = stmt.executeQuery(sql);
    %>
    <html>
    <head>
    <title>JSP + MYSQL Teszt</title>
    </head>
    <body>
    <a href="forum.jsp">Forum / Uj hozzaszolas</a>
    <a href="userlist.jsp">Felhasznalok kilistazasa</a>
    <a href="adduser.jsp">Felhasznalo hozzadasa</a>
    <a href="deletemessage.jsp">Hozzaszolas torlese</a>
    <br><br>
    <form action="addmessage.jsp" method=post">
    Felhasznalo:
    <input type="text" name="username">
    <br><br>
    Hozzaszolas:
    <input type="text" name="message">
    <br><br>
    <input type="submit" value="Uj hozzaszolas">
    <br><br>
    <table border="0">
    <tr>
    <th>messagecode</th>
    <th>user</th>
    <th>car type</th>
    <th>message</th>
    </tr>
    <%
      while(rs.next()){
    %>
    <tr>
    <td><%=rs.getInt("messagecode") %></td>
    <td><%=rs.getString("username") %></td>
    <td><%=rs.getString("bmwtype") %></td>
    <td><%=rs.getString("message") %></td>
    </tr>
    <%
      } // end while
    %>
    </table>
    </body>
    </html>
    <%
    } catch (Exception e) {
      out.println("<font color=red><h3>Error:</h3></font>" + e);
      e.printStackTrace();
    } finally {
      try {
        if (stmt!=null) {
          stmt.close();
        if (con!=null) {
          con.close();
      } catch (Exception e) {
        e.printStackTrace();
    %> ----
    addmessage.jsp
    <%@ page contentType="text/html; charset=iso-8859-2" %>
    <%@ page import="java.sql.*" %>
    <%
    Connection con = null;
    Statement stmt = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      String url =  "jdbc:mysql://localhost:3306/mysql";
      con =  DriverManager.getConnection(url,"root", "");
      stmt = con.createStatement();
    int rowsAffected = stmt.executeUpdate("INSERT INTO forummessages (messagecode, " +  " usercode, " + " messagedate,  " + " message) VALUES(6,3,06/07/2007,'" + a1 + "')");
    } catch (Exception e) {
      out.println("<font color=red><h3>Hiba:</h3></font>" + e);
      e.printStackTrace();
    } finally {
      try {
        if (stmt!=null) {
          stmt.close();
        if (con!=null) {
          con.close();
      } catch (Exception e) {
        e.printStackTrace();
    %>
    <a href="forum.jsp">Forum / Uj hozzaszolas</a>
    <a href="userlist.jsp">Felhasznalok kilistazasa</a>
    <a href="adduser.jsp">Felhasznalo hozzadasa</a>
    <a href="deletemessage.jsp">Hozzaszolas torlese</a>
    <br><br>---
    Thank you for your help in advance.

    SELECT DISTINCT
    hou.name
    ,poh.segment1 po_num
    ,pol.line_num po_line_num
    ,poh.currency_code
    --,trunc(poh.creation_date) po_creation_date
    ,pol.cancel_flag
    ,msi.segment1 item_num
    ,pol.unit_price
    ,round(cost.item_cost,5)
    ,round((&p_rate * pol.unit_price),5) "CONVERSION"
    ,(cost.item_cost - round((&p_rate * pol.unit_price),5)) difference
    ,pov.vendor_name
    FROM
    po.po_headers_all poh
    ,po.po_lines_all pol
    ,po.po_vendors pov
    ,hr.hr_all_organization_units hou
    ,inv.mtl_system_items_b msi
    ,bom.cst_item_costs cost
    WHERE
    poh.po_header_id = pol.po_header_id
    and pov.vendor_id = poh.vendor_id
    and poh.org_id = hou.organization_id
    and hou.organization_id = :p_operating_unit
    and poh.currency_code = :p_currency
    and poh.creation_date between :po_creation_date_from and :po_creation_date_to
    and poh.type_lookup_code = 'BLANKET'
    and msi.inventory_item_id = pol.item_id
    and cost.INVENTORY_ITEM_ID = pol.ITEM_ID
    --and (cost.item_cost - pol.unit_price) <> 0
    and (cost.item_cost - round((&p_rate * pol.unit_price),5)) <> 0
    and cost.organization_id = 1
    and msi.organization_id = 1
    and cost.cost_type_id = 3 --- Pending cost type
    and nvl(upper (pol.closed_code),'OPEN') not in('CANCELLED', 'CLOSED', 'FINALLY CLOSED', 'REJECTED')
    and nvl(upper (poh.closed_code),'OPEN') not in('CANCELLED', 'CLOSED', 'FINALLY CLOSED', 'REJECTED')
    and nvl(pol.cancel_flag, 'N') = 'N'
    and &p_rate user parameter
    I want this p_rate to be passed as a user parameter.

  • JSP MYSQL ERROR moving in resultset

    Hi I am new to jsp & mysql .
    I am trying to fetch data in a multiple select list box in my jsp page from a table in mysql . It fetches the first value and then exception is generated as no data found while there is data in the table . The same data in the table is fetched when i fetch in a dynamic table . I observed that i am having problems in fetching data only in list box . Please help me. It is a part of my project.
    Thanks

    Hi
    The code was generated my macromedia dreamweaver but still i'll writing it below:
    <select name="select" size="1" multiple>
    <%
    while (Recordset1_hasData) {
    %>
    <option value="<%=((Recordset1.getObject("overridetype")!=null)?Recordset1.getObject("overridetype"):"")%>"><%=((Recordset1.getObject("overridetype")!=null)?Recordset1.getObject("overridetype"):"")%></option>
    <%
    Recordset1_hasData = Recordset1.next();
    Recordset1.close();
    Recordset1 = StatementRecordset1.executeQuery();
    Recordset1_hasData = Recordset1.next();
    Recordset1_isEmpty = !Recordset1_hasData;
    %>
    </select>

  • XML, XSL - HTML(JSP), bad UTF-8 encoding on Tomcat

    I use simple transformation to create HTML (JSP) page from XML, XSL (both are encoded in UTF-8}. When doing this in embedded web server in JD9i developer, the result is fine. But when run at Tomcat 4.0.3, UTF-8 chars are displayed as 2 characters. It's interesting that the transformation gives different results:
    - in JD9i the UTF-8 chars are left unchanged and shown good in IE browser
    - in Tomcat the chars with acute (/) are transformed into "&iacute;" , "&aacute;" and so on and shown properly, whereas chars with caron (V) are encoded and shown badly.
    Does somebody know solution to this ? Thanks.

    Doing some more experiments reveals a subtle difference between GET and POST with Tomcat - it may apply to other application servers, but I have only tested with Tomcat 5 and Tomcat 6, so I can't say.
    The following is essentially what most people have indicated you need to do to have your JSP handle UTF-8:
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>My Title</title>
    </head>
    <body>
    </body>
    </html>This is what I couldn't get working with my GET (the default for forms) and ended up working when I specified the URIEncoding for the connector in the server.xml file.
    It turns out that the above will work with no modifications to the server.xml file if the form method is POST. If you need to be able use GETs then you will need to modify the connector, otherwise it would seem nothing you do at the JSP or servlet level will make a difference, unless you want to convert each parameter manually:
      String parameter = new String( request.getParameter("myParam").getBytes("ISO-8859-1"), "UTF-8" );Edited by: ajmasx on Sep 27, 2007 10:20 AM

  • Problems with MySQL in JSC 2

    i have problem with MySQL i have a driver i added it in to servers list and i made tests with data source everythink is ok, i see tables but when i drop a table from data source on table componenet(or other) i have errors nullPointerExpection at: (here is very long list of java classes. when i click "view data" of table in data source everythink works, only in components it doesn't. Can sombody help me please. I hope you understood my problem if not i will try to explain it once again.

    i get his Exception:
    A java.lang.NullPointerException exception has occurred.
    Please report this at http://www.netbeans.org/issues.html,
    including a copy of your messages.log file as an attachment.
    The messages.log file is located in your C:\Documents and Settings\Leszczy&#324;ski\.Creator\2_0\var\log folder.
    here are details:
    java.lang.NullPointerException
         at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:565)
         at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:507)
         at com.mysql.jdbc.PreparedStatement.toString(PreparedStatement.java:3290)
         at java.lang.String.valueOf(String.java:2577)
         at java.lang.StringBuffer.append(StringBuffer.java:220)
         at com.mysql.jdbc.trace.Tracer.printParameters(Tracer.aj:240)
         at com.mysql.jdbc.trace.Tracer.printEntering(Tracer.aj:167)
         at com.mysql.jdbc.trace.Tracer.entry(Tracer.aj:126)
         at com.mysql.jdbc.trace.Tracer.ajc$before$com_mysql_jdbc_trace_Tracer$1$f51c62b8(Tracer.aj:45)
         at com.mysql.jdbc.Connection.registerStatement(Connection.java)
         at com.mysql.jdbc.Statement.<init>(Statement.java:190)
         at com.mysql.jdbc.PreparedStatement.<init>(PreparedStatement.java:432)
         at com.mysql.jdbc.ServerPreparedStatement.asSql(ServerPreparedStatement.java:343)
         at com.mysql.jdbc.PreparedStatement.asSql(PreparedStatement.java:507)
         at com.mysql.jdbc.ServerPreparedStatement.toString(ServerPreparedStatement.java:2306)
         at java.lang.String.valueOf(String.java:2577)
         at java.lang.StringBuffer.append(StringBuffer.java:220)
         at com.mysql.jdbc.trace.Tracer.printParameters(Tracer.aj:240)
         at com.mysql.jdbc.trace.Tracer.printEntering(Tracer.aj:167)
         at com.mysql.jdbc.trace.Tracer.entry(Tracer.aj:126)
         at com.mysql.jdbc.trace.Tracer.ajc$before$com_mysql_jdbc_trace_Tracer$1$f51c62b8(Tracer.aj:45)
         at com.mysql.jdbc.Connection.registerStatement(Connection.java)
         at com.mysql.jdbc.Statement.<init>(Statement.java:190)
         at com.mysql.jdbc.PreparedStatement.<init>(PreparedStatement.java:414)
         at com.mysql.jdbc.ServerPreparedStatement.<init>(ServerPreparedStatement.java:280)
         at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4288)
         at com.mysql.jdbc.Connection.prepareStatement(Connection.java:4226)
         at com.sun.rave.sql.DesignTimeConnection.prepareStatement(DesignTimeConnection.java:187)
         at com.sun.sql.rowset.CachedRowSetXImpl.getMetaData(CachedRowSetXImpl.java:2334)
         at com.sun.data.provider.impl.CachedRowSetDataProvider.getMetaData(CachedRowSetDataProvider.java:1317)
         at com.sun.data.provider.impl.CachedRowSetDataProvider.getFieldKeys(CachedRowSetDataProvider.java:489)
         at com.sun.rave.web.ui.component.table.TableRowGroupDesignState.resetTableColumns(TableRowGroupDesignState.java:261)
         at com.sun.rave.web.ui.component.table.TableRowGroupDesignState.setDataProviderBean(TableRowGroupDesignState.java:163)
         at com.sun.rave.web.ui.component.table.TableDesignState.setDataProviderBean(TableDesignState.java:250)
         at com.sun.rave.web.ui.component.TableDesignInfo.linkBeans(TableDesignInfo.java:162)
         at com.sun.rave.insync.models.FacesModel.linkBeans(FacesModel.java:1042)
         at com.sun.rave.designer.DndHandler.processLinks(DndHandler.java:2126)
         at com.sun.rave.designer.DndHandler.importBean(DndHandler.java:880)
         at com.sun.rave.designer.DndHandler.importItem(DndHandler.java:702)
         at com.sun.rave.designer.DndHandler.importDataDelayed(DndHandler.java:376)
         at com.sun.rave.designer.DndHandler.access$000(DndHandler.java:114)
    [catch] at com.sun.rave.designer.DndHandler$1.run(DndHandler.java:298)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    yes i use JSC 2
    Is it posible that my MySQL is not working properly??
    Micz.

  • JSP - MYSQL HELP

    HI,
    Im trying to create a JSP which connects to a mysql database.
    I have downloaded all the connectivity drivers and dont know what to do from this stage.
    I have heard people talking about tomcat and apache but was wondering if i need them?
    Im new to all this connectivity bit so this is why i need help!!
    If anyone has any good links to some good jsp/mysql tutorials, please share!!!
    Thanks a lot

    You need a servlet/JSP engine, to start. You can't write or deploy a JSP without a servlet/JSP engine. Apache Tomcat is a good one to start with. It's free and robust:
    http://jakarta.apache.org/tomcat
    Here's a tutorial to get you started with servlets/JSP:
    http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
    Do a Google search or look at the Sun tutorials if you want more. - MOD

  • JSP/MYSQL Hosting

    Hey all,
    Im looking to host a JSP/MYSQL site. Please tell me a hosting provider. also are there any providers in India that you know of . would really help if tis the same country.
    after looking through a lot of sites i have shortlisted.
    http://www.eatj.com and http://4java.ca tell me if there is anything in the same budget range. Are there anybody who is availing these services. please give your comments on the same
    Thanks
    Ritesh

    google myjavaserver
    it's free, but slow and space limited...

  • JSP + MySQL + Linux + Tomcat4.1 Chinese display problem

    Hello all!
    I have a problem to use JSP to display Chinese which is read from MySQL database. It works well under Windows XP. But when I move the code to Linux. The Chinese can't be displayed any more.
    The only way to display Chinese correctly is to remove <%@ page contentType="text/html; charset=Big5" %>. This requires to set the browser encoding manually every time, which is not what I want.
    I am not sure if I need store the Chinese as Big5 or other unicode in MySQL. Right now, I just insert it into database directly without specifying the characters set.
    I have been searching for solutions for quite a while and can't get the answer. Please help me to conquer this problem!
    Below is the simplified version of my code:
    <html>
    <head>
    <%@ page contentType="text/html; charset=Big5" %>
    <%@ page import="java.util.*" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="ConnectionPool.*" %>
    <%@ page session="true" %>
    </head>
    <body>
    <table>                    
    <%
    ServletContext context = getServletContext();
    ConnectionPool connectionPool = (ConnectionPool)context.getAttribute("ConnectionPool");
    Connection connection = connectionPool.getConnection();
    Statement statement = connection.createStatement();
    String sqlCmd = "SELECT chinese_word FROM word";     
    String chinese_word;
    ResultSet rs = statement.executeQuery(sqlCmd);
    while (rs.next())
         chinese_word = rs.getString("chinese_word ");               
         out.println("<tr><td>" + chinese_word );
         out.println("</td></tr>");
    connectionPool.free(connection);
    %>
    </table>
    </body>
    </html>
    Thanks a bunch,
    Sophie

    hi
    i am india so no much command on chiness, but, as a solution process , i suggest this
    in jsp, response is the default object, so, whereever u want chiness char, use
    response.setContentType("text/html; charset=Big5");
    and again swith to normal english mode
    hope it proceeds...
    pranav

  • JSP Mysql Connection Problem

    Hi Friend,
    I am facing some problem in connecting mysql with jsp .
    When I try and connect to mysql with the following connection string
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdhiraj?user=root&password=dh");
    Statement statement     = con.createStatement();
    I get an error :
    java.sql.SQLException: Communication link failure: Bad handshake
    I don't know what is wrong,
    as I had tested mysql using telnet and it connects and executes sql nicely.
    Waiting for ur reply,
    Dhiraj Agrawal
    mail to : [email protected]

    Hi,
    You need to make sure that , you have given correct database name, user id and password in the connection url. and also check the jdbc driver is loaded properly. If your mysql is running in the standard port, you need not give the port as 3306.
    Here is the example :
    import java.sql.*;
         Notice, do not import org.gjt.mm.mysql.*
    or you will have problems!
    public class XampleClass
    public static void main(String[] Args)
    try {      
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    catch (Exception e) {
    System.err.println("exception while loading
    driver.");
    e.printStackTrace();
    try {
    Connection C = DriverManager.getConnection(
    "jdbc:mysql://localhost/test?user=myuser&password=mypwddb");
    // Do something with the Connection
    catch (SQLException e) {
    System.out.println("Exception: " + e);
    This is the format for conenction url :
    jdbc:mysql://[hostname][:port]/dbname[?param1=value1][&param2=value2]...
    Hope this helps you.
    Thanks,
    Senthil_Slash

  • [b][u]JSP/mySQL CREATE DATABASE problem[/u][/b]

    I am trying to create a mySQL DB through JSP program (query).
    The Query :
    stmt.executeUpdate("CREATE DATABASE employee;");
    is not working. PLEASE HELP ME.................
    The program is as follows.
    try
    Connection con =null;
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bedrock","Dude","");
    System.out.println("Connection Established");
    try {
    System.out.println("Entered Try Block");
    stmt=con.createStatement();
    stmt.executeUpdate("CREATE DATABASE employee;");
    System.out.println("Query Executed");
    catch(Exception e){ 
    System.out.println("Entered Catch Block");
    System.out.println("Query Skipped");
    catch (SQLException ex)
    while (ex != null){
    System.out.println("sql exception"+ex);
    ex = ex.getNextException ();
    Message was edited by:
    sam_john

    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bedrock","Dude","");
    Access denied for user: '[email protected]' (Using password: NO)
    You must provide a password for your connection.
    Your code should have been as follows:
    con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bedrock","Dude","YOUR_PASSWORD_HERE");Anyway, to create a database or a table in a db server like MySQL, you must have the good privileges to.
    Go to <MySQL_INSTALL_DIR>/Docs/ directory, you'll find there the MySQL manual.chm. Take a look at the the Tutorial section.
    In order to know how to use jdbc Connector/J, take a look at the documentation shipped with: /mysql-connector-java-X.X.X/docs/connector-j.html
    Here a typical code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    public class TestMySQL {
         public static void main(String[] args) {
              Connection con = null;
              Statement stmt = null;
              try {
                   Class.forName("org.gjt.mm.mysql.Driver").newInstance();
                   con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bedrock", "Dude", "YOUR_PASSWORD_HERE");////// put the right password here
                   System.out.println("Connection Established");
                   System.out.println("Entered Try Block");
                   stmt = con.createStatement();
                   stmt.executeUpdate("CREATE DATABASE employee");
                   System.out.println("Query Executed");
              } catch (Exception e) {
                   e.printStackTrace();
              } finally {
                   if (stmt != null) {
                        try {
                             stmt.close();
                        } catch (Exception e) {
                   if (con != null) {
                        try {
                             con.close();
                        } catch (Exception e) {
    }Hope That Helps

  • JSP & MySQL

    Hi!
    I am Pranay. I want to connect my JSP with MySQL. Will you please help me? I want the detail-code and pre-coding instructions.....
    General Informations:
    1. JDK 1.5.0
    2. Apache Tomcat 4.1
    3. MySQL Server 5.0
    4. MySQL Connector/J 5.0.4
    5. JAVA_CLASSPATH
    C:\Program Files\Java\jdk1.5.0\bin
    6. CLASSPATH
    C:\Program Files\mysql-connector-java-5.0.4
    Plz consider that I have a table in my MySQL database name tab1 which has fields: name,roll,date_of_birth.
    Thanx...

    The error you are getting looks like a network (socket) error rather than a JDBC or MySQL problem. The error indicates that a connection cannot be negotiated from Tomcat to MySQL. Are you sure MySQL is running on your laptop? Try to telnet to the MySQL port:
    (on windows, from the command prompt)
    C:\>telnet localhost 3306
    If this connects (the command promt screen should clear) then the problem is elsewhere, but my bet is you won't be able to connect this way either.
    If you cannot connect using telnet:
    1. Verify that MySQL is running on your laptop
    2. Verify that it's listening on port 3306
    3. Check that you don't have any local firewall apps blocking this traffic
    4. Verify that you don't have any manual host configurations which mean "localhost" points somewhere else (unlikely)
    If you CAN connect using telnet:
    1. Verify that your connection string is correct as per the MySQL JDBC Driver documentation
    2. Verify that your authentication credentials are correct (don't think it's this)
    Now... for a few supplimentary notes:
    You appear to be using the connection.isClosed() method to test whether you have a connection. This serves no purpose in the context you are using it as it's just a boolean which gets set when close() is called on the connection. ergo you could quite easily have a broken connection which returns "false" on an isClosed() call.
    Also, it is (strictly speaking) considered a better architecture to limit your JSP code to "display logic" only. This means it is usually void of any business logic or database-related code. You should really look at something like the MVC architecture (model-view-controller). This will save you a lot of headaches in the long run. If nothing else, debugging JSPs can be a real nightmare. I recommend you look at the Struts project (Apache Jakarta). It has become the defacto standard implementation of MVC.
    Good luck :)

  • JSPs with UTF-8 coding

    Dear all,
    I've got a problem in using JDeveloper 3.2.2 to write a JSP to connect to Oracle 8i database and display the query result.
    The database has been set to support UTF-8, and I've set the Encoding property of the complier of the project to "UTF-8". I included <%@ page contentType="text/html;charset=UTF-8"%> at the top of my JSP and <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"> inside the <Head> tags, but when I try to run under the JDeveloper, it fail to show the correct Chinese Characters, it shows some symbols...
    Is there any setting I've missed?
    Thanks
    LeeKit

    j2ee_ubuntu wrote:
    //BufferedReader fileReader = new BufferedReader(new FileReader(file)); //replace this with given below
    BufferedReader fileReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
    Nice spoon-feeding there. I assure you that the OP has learned exactly nothing now.

  • Problems with datagrid from FXP, I did something, but I got problems with mysql...

    Good night My name is Michel.
    Right!, I have a challenge to myself. that is to relearn flash builder, I have a few years without touching it or anything.
    But I still have the ease of get these new things added.
    Going straight to the point, as I am Brazilian, some things from the file will be in Portuguese, I hope you can help me! I appreciate it. Well, I'm creating a Datagrid, this Datagrid was done in FXP, and imported into the FB, I did some workarounds and got where I wanted, only that there are problems.
    the scheme is this:
    MySQL database = NoticiasService
    Connected by Zend / PHP.
    Everything right until here.
    I have the file main.mxml> DatalistSinspebNoticias.mxml> DatalistSinspebNoticiasRepeatedItemSkin.mxml - just here.
    I will not make a closed file (FXP), because my file is just a mess and only I understand the way it was organized.
    The problem is:
    The datagrid is infinite, I want to limit it to eight items repeated.
    The link does not work with "TextConverter" to "HTML"
    FB lives showing me glitches.
    then I will initiate an implementation of other applications, such as adding data to the DB, and Update DB. Thanks Folks!
    Main.mxml ------------------------------------------------------------------------->
    <?xml version='1.0' encoding='UTF-8'?>
    <s:Application xmlns:ATE="http://ns.adobe.com/ate/2009"
                                     xmlns:ai="http://ns.adobe.com/ai/2009"
                                     xmlns:fc="http://ns.adobe.com/flashcatalyst/2009"
                                     xmlns:d="http://ns.adobe.com/fxg/2008/dt"
                                     xmlns:fx="http://ns.adobe.com/mxml/2009"
                                     xmlns:s="library://ns.adobe.com/flex/spark"
                                     xmlns:lib="assets.graphics.caixa_feed_sinspeb.*"
                                     xmlns:flm="http://ns.adobe.com/flame/2008"
                                     xmlns:noticiasservice="services.noticiasservice.*"
                                     width="100%" height="100%" backgroundColor="#FFFFFF" preloaderChromeColor="#FFFFFF"
                                     fc:previewHeight="380" fc:previewWidth="430">
              <fx:Style source="Main.css"/>
              <fx:Script>
                        <![CDATA[
                                  import mx.events.FlexEvent;
                                  protected function list1_creationCompleteHandler(event:FlexEvent):void
                                            getAllNoticiasResult.token = noticiasService.getAllNoticias();
                        ]]>
              </fx:Script>
              <fx:Declarations>
                        <s:CallResponder id="getAllNoticiasResult"/>
                        <noticiasservice:NoticiasService id="noticiasService" showBusyCursor="true"/>
              </fx:Declarations>
              <fx:DesignLayer d:id="2" d:userLabel="Layer 1">
                        <s:List id="list1" x="10" y="8"
                                            creationComplete="list1_creationCompleteHandler(event)"
                                            skinClass="components.DataListSinspebNoticias" labelField="conteudo_nt">
                                  <s:AsyncListView list="{getAllNoticiasResult.lastResult}"/>
                        </s:List>
              </fx:DesignLayer>
    </s:Application>
    ------------------------------------------------------------------------->
    DatalistSinspebNoticias.mxml ------------------------------------------------------------------------->
    <?xml version="1.0" encoding="utf-8"?>
    <s:Skin xmlns:s="library://ns.adobe.com/flex/spark"
                        xmlns:fx="http://ns.adobe.com/mxml/2009"
                        xmlns:d="http://ns.adobe.com/fxg/2008/dt"
                        xmlns:flm="http://ns.adobe.com/flame/2008"
                        xmlns:ai="http://ns.adobe.com/ai/2009"
                        width="407" height="374">
              <fx:Metadata>[HostComponent("spark.components.List")]</fx:Metadata>
              <s:states>
                        <s:State name="normal"/>
                        <s:State name="disabled"/>
              </s:states>
              <s:DataGroup id="dataGroup" x="0" y="0" width="407" height="353" clipAndEnableScrolling="true"
                                             itemRenderer="components.DataListSinspebNoticiasRepeatedItemSkin"
                                             height.normal="374" buttonMode.normal="true">
                        <s:layout>
                                  <s:VerticalLayout gap="1"/>
                        </s:layout>
              </s:DataGroup>
    </s:Skin>
    ------------------------------------------------------------------------->
    DatalistSinspebNoticiasRepeatedItemSkin.mxml ------------------------------------------------------------------------->
    <?xml version="1.0" encoding="utf-8"?>
    <s:ItemRenderer xmlns:s="library://ns.adobe.com/flex/spark"
                                            xmlns:fx="http://ns.adobe.com/mxml/2009"
                                            xmlns:d="http://ns.adobe.com/fxg/2008/dt"
                                            xmlns:flm="http://ns.adobe.com/flame/2008"
                                            xmlns:ai="http://ns.adobe.com/ai/2009"
                                            width="402" height="39" autoDrawBackground="false">
              <fx:Script>
                        <![CDATA[
                                  import flashx.textLayout.conversion.ConversionType;
                                  import flashx.textLayout.conversion.TextConverter;
                        ]]>
              </fx:Script>
              <s:states>
                        <s:State name="normal"/>
                        <s:State name="hovered"/>
                        <s:State name="selected"/>
              </s:states>
              <s:Rect x="5" y="3" width="78" height="32">
                        <s:fill>
                                  <s:SolidColor color="#01557C"/>
                        </s:fill>
                        <s:stroke.hovered>
                                  <s:SolidColorStroke caps="none" color="#96F2FF" joints="miter" miterLimit="4" weight="2"/>
                        </s:stroke.hovered>
              </s:Rect>
              <s:Rect d:id="3" x="85.5" y="0.5" width="315" height="37" flm:variant="1"
                                  x.hovered="86" y.hovered="1">
                        <s:fill>
                                  <s:LinearGradient x="157.5" y="0" scaleX="32" rotation="90">
                                            <s:GradientEntry ratio="0" color="#FFFFFF"/>
                                            <s:GradientEntry ratio="0.488676" color="#E0EEF9"/>
                                            <s:GradientEntry ratio="1" color="#D6E9F7"/>
                                  </s:LinearGradient>
                        </s:fill>
                        <s:stroke>
                                  <s:SolidColorStroke caps="none" color="#666666" joints="miter" miterLimit="4" weight="1"
                                                                                    color.hovered="#999999" weight.hovered="2"
                                                                                    color.selected="#0065FF"/>
                        </s:stroke>
              </s:Rect>
              <s:Rect d:userLabel="Item Highlight Rectangle" x="5" y="0" width="396" height="33" alpha="0">
                        <s:fill>
                                  <s:SolidColor color="0xCED7EE"/>
                        </s:fill>
              </s:Rect>
              <s:RichText  x="20" y="12" width="48" height="14" ai:aa="2"
                                            color="#FFFFFF" columnCount="1" fontFamily="Myriad Pro" fontSize="14" kerning="on"
                                            tabStops="S0" text="{data.datada_nt}" flm:variant="2" whiteSpaceCollapse="preserve"/>
              <s:RichText x="89.95" y="8" width="309" height="24" ai:aa="2" color="#000000" columnCount="1"
                                            fontFamily="Arial Narrow" fontSize="11" kerning="on"
                                            tabStops="S0 S50 S100 S150 S200 S250 S300"
                                            textFlow="{TextConverter.importToFlow(data.conteudo_nt, TextConverter.TEXT_FIELD_HTML_FORMAT)}"
                                            trackingRight="16%"
                                            flm:variant="3" whiteSpaceCollapse="preserve"
                                            buttonMode.normal="false" lineThrough.normal="false">
                        <s:filters>
                                  <s:GlowFilter alpha="1.0" blurX="0" blurY="0" color="#000000" inner="false"
                                                                  knockout="false" quality="2" strength="1"/>
                        </s:filters>
              </s:RichText>
              <s:Path includeIn="hovered" x="0.35" y="12.35" data="M 12.40 7.15 L 0.03 14.29 0.03 0.01 Z ">
                        <s:stroke>
                                  <s:SolidColorStroke caps="none" color="#666666" joints="miter" miterLimit="4" weight="1"/>
                        </s:stroke>
                        <s:fill>
                                  <s:LinearGradient rotation="90">
                                            <s:GradientEntry color="#FFFFFF" ratio="0"/>
                                            <s:GradientEntry color="#E0EEF9" ratio="0.488676"/>
                                            <s:GradientEntry color="#D6E9F7" ratio="1"/>
                                  </s:LinearGradient>
                        </s:fill>
              </s:Path>
    </s:ItemRenderer>
    ------------------------------------------------------------------------->

    The following says how to restore from backup.
    iOS: How to back up
    If you go to iTunes>Preferences>Devices you can see if you have an iTunes backup. You need one dated before or the exact time you started the restore.

  • JDBC/JSP/MySQL Code works from my local machine, but not on server

    Hi there!
    I've been struggling with this problem for a while.
    I have a database from which I need to read and display some data on a browser. (The database is set up for remote access).
    I'm using the following JSP/JDBC code to do that.
    Class.forName ("com.mysql.jdbc.Driver").newInstance();
    out.println("<BR> Connecting to DB...Pls. Wait <BR>");
    Connection con = DriverManager.getConnection("url","user","pwd");
    if(con.isClosed())
    out.println("<BR><BR><BR>" +"Could NOT connect to MySQL Database...");
    else out.println("<BR> CONNECTED !!! <BR>");
    Statement stmt = con.createStatement();
    results = stmt.executeQuery("SELECT * FROM TableName" );
    When I run this of my local machine, it works fine. But when I upload it to a server, it doesn't run through. I dont get either the connected or not connected message.
    I tried this piece of code that I found online to check the driver.
    /*Driver d = (Driver)Class.forName("com.mysql.jdbc.Driver").newInstance();
    out.println("<BR>Got a driver instance. ");
    if (d.acceptsURL(url)) out.println("<BR>The driver does accept my URL");
    else out.println("<BR>The driver doesn't like the URL I'm trying"); */
    I ran it off the server and it worked. I got the outputs --Got a driver instance and The driver does accept my URL
    I'm unable to figure out why this code can be run locally from my machine, but not from a different location. The database is NOT on my machine.
    Any inouts will be really appreciated.
    I'm using an Apache Tomcat container and the database is MySQL.

    Just wanted to mention
    The database is on another (3rd) machine.
    So I have
    1. My local machine
    2. Database hosted on a 2nd machine
    3. Place I'm moving my code to (its basically a hosting account provided by an external company)
    I can access the database from my local machine. However, when I move the code over to another machine, it doesn't work.

Maybe you are looking for