Java. MySQL, JPEG Blob

Pardon the length of the thread, but I just want to make sure we follow each other to the end.
So now, am having a MySQL database, with a table thus:
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);Into this table I upload a jpg picture through the code:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package nmsquery;
* @author Arthur
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
class FileMySQLSaver
    public static void main(String[] args) throws FileNotFoundException, IOException
        File file = new File("C:\\Users\\Arthur\\Desktop\\africa.jpg");
        System.out.println("Saving file " + file.getName() + " of size " + (file.length()/1000) + " KB");
        saveFile(file);
    private static void saveFile(File file)
        try
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:mysql://10.0.0.118:3306/test?", "arthur", "password");
            String INSERT_PICTURE = "insert into upload(name, type, size, content) values (?, ?, ?, ?)";
            FileInputStream fileInputStream = null;
            PreparedStatement preparedStatement = null;
            try
                conn.setAutoCommit(false);
//      File file = new File("myPhoto.png");
                fileInputStream = new FileInputStream(file);
                preparedStatement = conn.prepareStatement(INSERT_PICTURE);
                preparedStatement.setString(1, file.getName());
                preparedStatement.setString(2, file.getCanonicalPath().substring(file.getCanonicalPath().length() - 3));
                preparedStatement.setInt(3, (int) file.length());
                preparedStatement.setBinaryStream(4, fileInputStream, (int) file.length());
                preparedStatement.executeUpdate();
                conn.commit();
            finally
                preparedStatement.close();
                fileInputStream.close();
        catch (Exception e)
            e.printStackTrace();
}That runs ok.
So now I want to do the reverse - take the picture from MySQL and display it as a web page. So I employ a jsp page (yes I know this aint the right way to go about it, but at least its the fastest)
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Blob</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  </head>
  <body>
    <%
            try
                // Declare some constant values
                final String user = "arthur";
                final String password = "password";
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test?", user, password);
                Statement statement = connection.createStatement();
                String query = "SELECT * FROM upload";
                ResultSet rs = statement.executeQuery(query);
                // Get the results
                while (rs.next())
                    out.print(rs.getBytes("content"));
                connection.close();
            catch (Exception e)
                out.print(e);
                out.print("Your session has expired");
    %>
  </body>
</html>Which, fortunately or not, displays only this:
[B@1ae76 Now am tempted to think that maybe the line in the jsp file
out.print(rs.getBytes("content"));might be the one responsible. Or is it?

BalusC wrote:
A couple of flaws:
1) Images in HTML are to be represented in an <img> tag where the 'src' points to nothing else than the bytes of the image.That I agree
2) The [Object#toString()|http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()] of a byte[] doesn't give you the bytes of the image. You need to write the bytes as bytes to the outputstream of the response. Along nothing else.Allow me to ask how to do this
3) Your code is leaking DB resources. Close resultset, statement and connection in the finally block. Otherwise your application will crash sooner or later.Noted, thanks
You may find this example useful: [http://balusc.blogspot.com/2007/04/imageservlet.html].
I notice that the examples show how to read from canonical or absolute file paths. There isn't anything on reading from a blob...

Similar Messages

  • Java mysql OK with Terminal but not OK with Apache local web server

    With terminal I have :
    CLASSPATH=/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Classes/:/Library/Java/Extensions/:./
    SUDO_GID=20
    SECURITYSESSIONID=210800
    _=/usr/bin/printenv
    127:/Library/WebServer/Documents/Java root# java TestMySQL
    2006-05-21 13:39:00.0 ************************************************** = OK
    127:/Library/WebServer/Documents/Java root#
    import java.sql.*;
    * mysql-connector-java-3.1.12-bin.jar
    *   % javac /Library/WebServer/Documents/Java/TestMySQL.java
    *   % java TestMySQL
    public class TestMySQL {
            public static void main(String argv[]) throws Exception {
                    // Load the driver class
                    Class.forName("org.gjt.mm.mysql.Driver");
    1                //Class theClass = null;
    2               //try {
    3                //    theClass = Thread.currentThread().getContextClassLoader().loadClass("org.gjt.mm.mysql.Driver");
    4                //}
    5                //catch (ClassNotFoundException e) {
    6                //    theClass = getClass().getClassLoader().loadClass("org.gjt.mm.mysql.Driver");
    7                //}
                    Connection conn = DriverManager.getConnection(
                            "jdbc:mysql:///test",
                    Statement stmt = conn.createStatement();
                    ResultSet rset = stmt.executeQuery("SELECT now();");
                    while (rset.next()) {
                            System.out.println(rset.getString(1));
                    // Close result set, statement and DB connection
                    rset.close();
                    stmt.close();
                    conn.close();
    }I have a simple TestMySQL.html file with applet TestMySQL.class in it.
    Nothing but "Applet TestMySQL not inited"
    When I uncomment the try/catch lines (lines 1 to 7) , java compiler generate an error... near getClass().getClassLoader().loadClass("org.gjt.mm.mysql.Driver");
    With "Class.forName("org.gjt.mm.mysql.Driver");" no problem.
    Running MacOS X 10.3.9, Apache/1.3.33 (Darwin) PHP/4.4.1 mod_ssl/2.8.24 OpenSSL/0.9.7i and JVM 1.4.2_09
    Thanks for help.
    P.S. This my first approach to java/mysql but I would like to see this short program running on my local web server ...
    Thanks.

    hi :-)
    can you post the stack trace?
    im not sure what is causing the error because of less info,
    but have you tried to copy the driver of mysql to tomcat lib folder?
    regards,

  • How to do transactions in jsp pages using Java & MySQL ?

    Hi,
    I'm a newbie..
    I'd like to know "How to do transactions in jsp pages using Java & MySQL ?"
    Platform: Windows XP, Apache Tomcat 5.5, MySQL 5, Java bean without EJB
    what are the the different types of transactions? Differences between them?Pls provide examples?
    Which among them is the best method to implement a transaction?
    Pls help me...
    thnx in advance...

    http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

  • Java.sql.SQLExcepton: Blob not found

    I'm working with IDS7.3 Informix Database on Unix,
    jdk1.3, jdbc2.10, Jakarta-Tomcat Webserver 3.x.
    When I want to select content from BYTE type
    (content is Word document) in database
    with code line: rset.getBytes(1);
    I got next exception:
    java.sql.SQLException: Blob not found
         at com.informix.util.IfxErrMsg.getSQLException(IfxErrMsg.java:308)
         at com.informix.jdbc.IfxResultSet.blobCheck(IfxResultSet.java:1548)
         at com.informix.jdbc.IfxResultSet.getBytes(IfxResultSet.java:1042)
         at com.informix.jdbc.IfxResultSet.getBytes(IfxResultSet.java:1057)
         at com.mis.upravljanjedokumentima.MISDocument.preuzmiDokumenteZaQuery(MISDocument.java:2235)
         at Web.administration.jsp.d_00025kumenti._0002fWeb_0002fadministration_0002fjsp_0002fdokumenti_0002fNaslovnaStranaDokumentiView_0002ejspNaslovnaStranaDokumentiView_jsp_0._jspService(_0002fWeb_0002fadministration_0002fjsp_0002fdokumenti_0002fNaslovnaStranaDokumentiView_0002ejspNaslovnaStranaDokumentiView_jsp_0.java:162)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:126)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:174)
         at org.apache.jasper.runtime.JspServlet.serviceJspFile(JspServlet.java:261)
         at org.apache.jasper.runtime.JspServlet.service(JspServlet.java:369)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.handleRequest(ServletWrapper.java:503)
         at org.apache.tomcat.core.ContextManager.service(ContextManager.java:559)
         at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:160)
         at org.apache.tomcat.service.TcpConnectionThread.run(SimpleTcpEndpoint.java:338)
         at java.lang.Thread.run(Unknown Source)
    What is wrong!???
    Thanks

    Make sure it isn't NULL. When you create the record, make sure you are setting that field to empty_blob().

  • JDBC Java- mysql problem help!

    Hi, I wnat to connect to mySQL fromo Java, I followed all the instructions from the mySql web page, yet I havent been able to do it, when I compile the java progrm I keep getting class not found exceptions, I am using Fedora Core and Java was already installed-well I chose to install it when I installed the operating system, the point is that the paths are all assigned by he system not by me.
    WHat can I do?, Ive been trying over andover again with no results, hopefully somebody can help, I tried to include all the configuration in this email,
    thank you
    my java program is the following:
    t.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class t {
    public static void main (String[] args) {
    System.out.println("Hello, world!\n");
    Class.forName("com.mysql.jdbc.Driver");
    when I javac t.java
    I have the following error
    4. ERROR in t.java
    (at line 11)
    Class.forName("com.mysql.jdbc.Driver");
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    Unhandled exception type ClassNotFoundException
    when I comment out the Class.forName the hello world rogram runs fine
    when I vi /etc/java java.conf this is the result
    # System-wide Java configuration file -- sh --
    # JPackage Project [www.jpackage.org]
    # Location of jar files on the system
    JAVA_LIBDIR=/usr/share/java
    # Location of arch-specific jar files on the system
    JNI_LIBDIR=/usr/lib/java
    # Root of all JVM installations
    JVM_ROOT=/usr/lib/jvm
    # You can define a system-wide JVM root here if you're not using the default one#JAVA_HOME=$JVM_ROOT/java-gcj
    # Options to pass to the java interpreter
    JAVACMD_OPTS=
    ~
    [root@localhost test]# echo $PATH
    /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
    echo $JAVA_HOME
    it contains nothing
    ls /usr/share java*
    java
    java-1.3.0
    java-1.4.0
    java-1.4.1
    java-1.4.2
    java-1.5.0
    javadoc
    java-ext
    java-utils
    mysql-connector-java-3.1.13-bin.jar is under
    /usr/share/java
    in /etc/profile I have:
    export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-3.1.13-bin.jar
    in /root/.bash_profile i have
    CLASSPATH=/usr/share/java/mysql-connector-java-3.1.13-bin.jar:/usr/lib/java-ext/mysql-connector/mysql-connector-java-3.1.13-bin.jar
    export CLASSPATH
    when I echo $PATH i have
    /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin

    Thanks duff,
    The driver seems to be found
    when I run
    public class t {
    public static void main (String[] args) {
    try
    System.out.println("Hello, world!\n");
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("MySQL Driver Found");
    catch (ClassNotFoundException e)
    System.out.println("MySQL Driver NOT Found");
    e.printStackTrace();
    I feel somehow ive been focusing in the wrong side of the problem due to my ignorance in Java. Please help me to understand, the reson for which ithe runtime was telling me that there was an unhandled exception was because it is a requirement to handle all exceptions of this kind? why wouldnt it cmplain if I jst did the hello world without any exception handling, maybe because it is a requirement in the Class.forName...
    the other question is, is the message I was obtaining completely independent of the fact that the class was or was not found?
    Maybe, I should go with these questions to the newbies forum...
    thanks

  • Java mysql connection

    Hi,
    Can anybody tell me how can I make the java-mysql JDBC connection using IDS Server ( type 3 driver )
    this is the only driver which bypass proxy/firewall
    if any one use this driver before pls give me more information about it.

    Well, first you have to obtain a type 3 driver for MySQL. I don't know if such a driver exists.
    Assuming one does, you'd need a properly configured server.
    Once you've got that, the Java code should be identical to that for any other driver.

  • MySQL and Blobs

    Hey everyone,
    Small question:
    How can I get a string from a Blob (org.gjt.mm.mysql.jdbc2.Blob)? I tried this:
    Blob b = ...;
    String str = new String(b.getBytes(0, (int)b.length()));but that gave me an ArrayIndexOutOfBoundsException. How can I do it?
    Thanks on advance,
    Nille

    That was a confused 'mmm', that a 'you suck' 'mmm'. That would be more like 'hmm' or perhaps 'grmpf'.
    I really appreciate your help, and I'm sorry if I wasn't clear about this.
    Anyway, the new driver solved it. The implementation was poor.
    Nille

  • Simple java/mysql database application question about triggers

    I am planning a new database application using java and mysql. I may want to use some triggers to automatically update the tables when a change is made. my question is this: If I write the trigger, and I use Java to modify the database, will java automatically pause and let the trigger finish doing its task before it continues? what if it writes more to the table before the trigger is finished modifying the table? how do I get java to pause and let the trigger finish?
    thanks for your response

    lduren wrote:
    I am planning a new database application using java and mysql. I may want to use some triggers to automatically update the tables when a change is made. my question is this: If I write the trigger, and I use Java to modify the database, will java automatically pause and let the trigger finish doing its task before it continues? what if it writes more to the table before the trigger is finished modifying the table? how do I get java to pause and let the trigger finish?
    It doesn't have anything to do with java at that point.
    When you execute, for example, an insert statement, then the database executes that statement. The database (not java, not the driver) decides with that statement is complete. Control returns to java when the database decides that execution is complete.
    And except for tricks that one might do (or attempt to do) via SQL or triggers then when the statement execution finishes then everthing has completed running.

  • I need to learn how to use all about java & mysql...help me!

    I have a situation here, I need to learn how to use java with mysql
    . Can I connect to a MYSQL DB with servlets?
    how can I build an e-mail server with java (no matter how difficult)
    please, I need help, and I really apreciate your help.
    thank you very much!!

    I have a situation here, I need to learn how to use
    java with mysql
    . Can I connect to a MYSQL DB with servlets?Yes... documentation to help you connect to any database can be found at http://java.sun.com/products/jdbc. To connect to MySQL, you'll need drivers (sourceforge.net), and the specific connection URL for those drivers will be included in the documentation.
    how can I build an e-mail server with java (no matter
    how difficult)If you're fairly new to JSP/Servlets, you may be in over your head here, since an email server is no easy application to code. Here's a link to the source code for the JAMES project... Apache's Java email server... maybe you can find some useful information there...
    http://www.ibiblio.org/pub/packages/infosystems/WWW/servers/apache/jakarta/james/source/

  • Java & MySQL in linux

    Hi,
    i installed Mandrake Linux and clicked for it to install MySQL when installed. how do i enter records and create a mysql database? what do i click on to start it? do i use telnet or shell, what do i type in? how do i call a mysql data base from a java program? (i can get it to work in windows, but just installed linux today.
    eat lot of turkey,
    L

    i tried running
    shell> rpm -qpl MySQL-VERSION.i386.rpm
    but got the error error: open of MySQL-VERSION.i386.rpm failed: No such file or directory
    but when i type
    whereis mysqli get
    /usr/bin/mysql /usr/share/mysql /usr/share/man/man1/mysql.1.bz2
    does that mean its already installed, is there a readme file or something similar?
    ty
    abe

  • Problem in running a program in java mysql

    i have a lot of nested java programs, individual testting results are ok, how ever, the following results occur when i combine those codes, do you have any idea about this? sorry about this but i hope you can help me.... thanks in advance....
    false
    true
    java.sql.SQLException: Illegal operation on empty result set.
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:680)
    at com.mysql.jdbc.ResultSet.getStringInternal(ResultSet.java:5021)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:4999)
    at checkvalidity.tesdiscode(checkvalidity.java:44)
    at forplay.play(forplay.java:7)
    at test1.main(test1.java:27)
    false
    java.sql.SQLException: Illegal operation on empty result set.
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:680)
    at com.mysql.jdbc.ResultSet.getStringInternal(ResultSet.java:5021)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:4999)
    at checkvalidity.tesdiscode(checkvalidity.java:44)
    at forplay.play(forplay.java:19)
    at test1.main(test1.java:27)
    java.sql.SQLException: Illegal operation on empty result set.
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:680)
    at com.mysql.jdbc.ResultSet.getStringInternal(ResultSet.java:5021)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:4999)
    at checkvalidity.tesdiscode(checkvalidity.java:44)
    at forplay.play(forplay.java:31)
    at test1.main(test1.java:27)
    java.sql.SQLException: Illegal operation on empty result set.
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:680)
    at com.mysql.jdbc.ResultSet.getStringInternal(ResultSet.java:5021)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:4999)
    at checkvalidity.tesdiscode(checkvalidity.java:44)
    at forplay.play(forplay.java:34)
    at test1.main(test1.java:27)
    Sorry, you have submitted an invalid promo code. Please try again. To send more
    entries text SMB PLAY <Promocode> to 2622. Ex. SMB Play abcd123. To start playin
    g games log-on to www.smbplay.com/activ8 Create ur group, play & win as a team,
    text SMB GROUP to 2622. To learn mre abt this promo text SMB HELP. Mre points, m
    re games, mre chances of winning! Promo pd is fr Jul 1�06 � Jul 1 �07. BFAD#dean
    silver. P2.50/txt
    C:\jwork\smbcode>javac test1.java
    test1.java:24: ')' expected
    System.out.println(checkvalidity.tesdiscel("639155510003");
    ^
    1 error

    about this code:
    C:\jwork\smbcode>javac test1.java
    test1.java:24: ')' expected
    System.out.println(checkvalidity.tesdiscel("639155510003");
    ^
    1 error
    i solved this one, the upper is the problem, i made a class for handling mysql - inputting and retrieving datas, the other classes are handling conditional outputs and the actual outputs. the later part of the output is, however, correct, the text that i prepared for the condition class... but still, the problem is that there are a lot of sql exceptions that i don't understand, i do appreciate if you help me more, thank you, by the way, how can i give out duke dollars for the guys who helped me?

  • Java MySQL  ResultSet Help

    How do I read the result of query -
    "SELECT unix_timestamp(date_format(now(), '%Y-%m-%d %H') )"
    from Java Result Set to a String variable in Mysql..
    I tried -
    Connection conn = getConnection( );
    Statement s = connection.createStatement();
    ResultSet rs = s.executeQuery( "SELECT unix_timestamp(date_format(now(), '%Y-%m-%d %H') )" );
    String result = resultSet.getString( "unix_timestamp(date_format(now(), '%Y-%m-%d %H') )");
    I don't get the value in result..rather I get the exception...My resultSet comes as not null from database.
    Thanks!

    You are using one variable when executing query and using another variable when accessing data. See the bolded values.
    Connection conn = getConnection( );
    Statement s = connection.createStatement();
    ResultSet rs = s.executeQuery( "SELECT unix_timestamp(date_format(now(), '%Y-%m-%d %H') )" );
    String result = resultSet.getString( "unix_timestamp(date_format(now(), '%Y-%m-%d %H') )");

  • Java mysql?

    I am writing a small java program which contects to mysql. And was trying to setup the databases in mysql, I wondered if anyone could see a logical error in this sql statement. I hope related java questions are allowed in the forum? sorry if not.
    create table(user VARCHAR(255), registered DATETIME, purchase ENUM('y','n'), total INT, PRIMARY KEY(user, registered);
    Thank you

    Hello,
    I was just looking at the mysql site, for keywords DATETIME, ENUM.
    The site does not mention how these shouble be delclared in a create able line.
    Though I have seen an other example on the web, and they used DATETIME DEFAULT '0000-00-00 00:00:00'
    Do you think the DEFAULT keyword must be used with DATETIME. I could not find anything on the mysql site to confirm this?
    Thanks

  • Java mysql connectivity

    hi
    i m trying to connect to mysql database through java. i have mysql-java-connector jars file placed in the JAVA_HOME\jre\lib\ext directory.
    now when i try to run this file its starts givin me this error...............
    Exception in thread "main" java.lang.NoClassDefFoundError: Test
    the java file that im running is this............(Test.java)
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.*;
    class Test
         public static void main(String args[])
              System.out.println("Hello");
              System.out.println("Welcome to the world of java");
              System.out.println("Lets learn java.");
              String url="jdbc:mysql://localhost:3306/database";
              Connection con = null;
              Statement stmt = null;
              ResultSet rs = null;
              String query;
              try {
              try{
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
              catch(Exception e)
                   System.out.println("driver not found"+e.getMessage());
                   con = DriverManager.getConnection (url, "", "");
                   stmt = con.createStatement();
                   query = "select * from test;";
                   ResultSet result = stmt.executeQuery(query);
                   while(result.next())
                   String callNumResult = result.getString("name");
                   System.out.println(callNumResult);
              catch(Exception e)
                   System.out.println("SQLException caught: " + e.getMessage());
              finally {
                   try {
                        if (con != null) con.close();
                   catch (SQLException e) {}
    i have also tried adding that mysql-java connector jar file to the classpath........
    but all in vain.....the error persists.
    plz help me with it.........
    ankur

    hi
    i m trying to connect to mysql database through java.
    i have mysql-java-connector jars file placed in the
    JAVA_HOME\jre\lib\ext directory.That's a terrible place to put them. Only language extensions (e.g., packages that start with javax) belong in there. Put that JAR closer to your application.
    >
    now when i try to run this file its starts givin me
    this error...............
    Exception in thread "main"
    java.lang.NoClassDefFoundError: TestLook at the exception: it's complaining about Test, NOT the MySQL JDBC driver class.
    You obviously don't understand how CLASSPATH works:
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html
    I think you have to add the current directory to the CLASSPATH in order to run your Test:
    java -classpath . TestNote the "dot" after -classpath. That tells the class loader to start looking in the current directory. since your Test.java doesn't have a package statement, I'm assuming that Test.class is in the same directory as Test.java.
    >
    >
    >
    the java file that im running is
    this............(Test.java)
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.io.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.*;
    class Test
    public static void main(String args[])
    System.out.println("Hello");
    System.out.println("Welcome to the world of java");
    System.out.println("Lets learn java.");
    String url="jdbc:mysql://localhost:3306/database";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    String query;
    try {
    try{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    catch(Exception e)
    System.out.println("driver not found"+e.getMessage());
    con = DriverManager.getConnection (url, "", "");
    stmt = con.createStatement();
    query = "select * from test;";
    ResultSet result = stmt.executeQuery(query);
    while(result.next())
    String callNumResult = result.getString("name");
    System.out.println(callNumResult);
    catch(Exception e)
    System.out.println("SQLException caught: " +
    e.getMessage());
    finally {
    try {
    if (con != null) con.close();
    catch (SQLException e) {}
    i have also tried adding that mysql-java connector jar
    file to the classpath........
    but all in vain.....the error persists.
    plz help me with it.........
    ankur

  • Question about Java MySQL connection

    Hi guys, greetings to y'all, me name is Ryan, I'm new 'round here.
    I have some questions, I have some application that I build with Java and using MSSQL Server 2000 as it's database, and now I want to try to use MySQL as it's database. I use MySQL server 5.0 and Navicat 8 for MySQL for the gateway and Win XP SP2 as my OS, what I want to know is, can you guys give me some connection string example for MySQL, for Java that is, I'm still learning in Java so sorry if I have some mistaken languages or code related words. Thanks a lot guys.
    Best Regards.

    Hi zahid, thanks for the reply, so if I have this code, like this one
    try
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                  Connection con;
                                  con=DriverManager.getConnection("jdbc:odbc:FlightSource","","");
                                  stat2=con.prepareStatement("insert into Passenger_Table(vPassenger_Name,vPassenger_gender,iPassenger_Age,vPassenger_Destination,vPass_FlightClass,vPass_FlightType,vDate_of_Issue,vDate_of_Departure,vDate_Expire,vForm_Payment,Card_No,vTotal_Price)values(?,?,?,?,?,?,?,?,?,?,?,?)");
                                  stat2.setString(1,textNama.getText());
                                  stat2.setString(2,(String.valueOf(entry2)));
                                  stat2.setString(3,textUmur.getText());
                                  stat2.setString(4,textTujuan.getText());
                                  stat2.setString(5,(String)comboKelas.getSelectedItem());
                                  stat2.setString(6,(String)comboJenisKeberangkatan.getSelectedItem());
                                  stat2.setString(7,(String)comboTglTiket.getSelectedItem()+"/"+texttgltiket1.getText()+"/"+texttgltiket2.getText());
                                  stat2.setString(8,(String)comboTglBerangkat.getSelectedItem()+"/"+texttglberangkat1.getText()+"/"+texttglberangkat2.getText());
                                  stat2.setString(9,(String)comboTglKadaluwarsa.getSelectedItem()+"/"+texttglkadaluwarsa1.getText()+"/"+texttglkadaluwarsa2.getText());
                                  stat2.setString(10,(String)comboPayType.getSelectedItem());
                                  stat2.setString(11,textCardNo.getText());
                                  //stat2.setFloat(12,Float.parseFloat(textHarga.getText()));
                                  stat2.setString(12,textHarga.getText());
                                  stat2.executeUpdate();
                                  JOptionPane.showMessageDialog(null, "The Data has successfully Booked " );
                             catch(Exception exception)
                                  JOptionPane.showMessageDialog(null,"Error encountered while entering data in the database: "+exception);
                             }I just simply change the Class.forName{} line right ?
    What About the database name, considering in the code above I used ODBC (the ODBC name is FlightSource), so the database was configured when I create the ODBC, then how about MySQL, should I create ODBC too to configured the database that I wanna use ?

Maybe you are looking for

  • Doubt in loading Driver

    I am connecting to Oracle Database. I have written the following code to connect to a database 1 Class.forName("oracle.jdbc.driver.OracleDriver"); 2 con = DriverManager.getConnection ("jdbc:oracle:thin:URL","USERNAME","PASSWORD"); 3 st = con.createSt

  • How to retard tcp ack

    Hi all! I'd like to know if it is possible to retard the tcp ack. I'll try to explain me better: I am receiving important data through tcp: when I receive this data I don't want to send immediately the ack packet: it may occur that i receive the pack

  • Ipod Touch Wifi Intermittent Connectivity

    I have seen the questions already on the Forum but I cannot find a solution. I have 1st gen Ipod Touch 32GB, latest version 3.0 software, Belkin N+ Wirelss set up. Sony Laptop connects 100% time, Ipod Touch connects OK but after between 2-5 minutes i

  • IBooks Author Keep crashing (tried reinstall)

    I am using new macbook Pro with OSX 10.8.2 after i download and open iBooks Author, it just crash 10 seconds later. Tried many times, and then i reinstall and restart the computer, but it doesnt help.

  • Regarding "select into" query and "no data found" exception

    So i have included the following into my procedure: select div_cd into c_div_cd                from division_tab d, emp_tab y                where d.div_name=y.div_text and y.emp_code=d.emp_code; and also an exception exception when no data found --