MySql with java

hi all,
I got one problem with MySql ..
I am using MySql for database but I got problem while start the
MySql that is Not found the Driver...
i think the problem is path I have not set the path for MySql
So please tell me if anyone knows how to set the path ....
Error message in MySql is > Driver 3.51 Not Found
I Installed the MySQl in the D\mysql and start the mysql
So please tell me ...
thanks.........

does this question have anything to do with Java or is it what it appears to be... a problem with mysql. if it is you are on the wrong site doncha think... try the mysql website http://www.mysql.com/

Similar Messages

  • Using MySQL with Java

    Hi, I am writing a database program, and I decided I should try and use MySQL since many people have told me it is the best way to make a database. Does the java version that Sun provide come with the api to create mysql databases?
    Also, I would like to know of a good tutorial that teaches MySQL with java.

    Hi, I am writing a database program, and I decided I
    should try and use MySQL since many people have told
    me it is the best way to make a database. Does the
    java version that Sun provide come with the api to
    create mysql databases?
    You are more than a bit confused so please stop here until you understand the following.
    JDBC is the API for communicating with relational databases in Java. It is not a database in and of itself but it can communicate with any database that provides JDBC API access in the form of a JDBC driver.
    Also, I would like to know of a good tutorial that
    teaches MySQL with java.The Sun tutorial on JDBC may be found here http://java.sun.com/docs/books/tutorial/jdbc/index.html
    Your using (or not) MySQL is not relevent on this forum and any questions you have regarding MySQL (with the exception of one) are beyond the scope of this forum.
    The exception is "Is there a JDBC driver for MySQL and how do I use it". The answer to that question is yes and see this http://www.mysql.com/products/connector/j/

  • Problem is establishing connection with MYSQL with JAVA on windows

    i have installed MYSQL 3.23.54 for window XP and a JDBC connector mysql-connector-java-2.0.14.
    i have set the classpath for JDBC driver as
    C:\> set CLASSPATH=\path\to\mm.mysql.jdbc-[version];%CLASSPATH%
    and my code for testing the connection is
    import java.sql.*;
    public class Connect
         public static void main (String[] args)
              Connection conn = null;
              try
                   String userName = "saqib";
                   String password = "123";
                   String url = "jdbc:mysql://localhost/test";
                   Class.forName ("org.gjt.mm.mysql.Driver").newInstance ();
                   conn = DriverManager.getConnection (url, userName, password);
                   System.out.println ("Database connection established");
              catch (Exception e)
                   System.err.println ("Cannot connect to database server");
              finally
                   try
                        if (conn != null)
                             conn.close ();
                             System.out.println ("Database connection terminated");
                   catch (Exception e) { /* ignore close errors */ }
    . the problem i'm facing is that when i compile and run the program the following message is generated.
    Exceprion in thread "main" java.lang.NoClassDefFoundError: Coonect
    please help me out to establist the connection. is the classpath which i have set is correct. i have placed the unziped driever in the folder c.
    thanks
    Saqib

    Maybe you should have typed "Connect" instead of "Coonect" at the command line?

  • Deploying Mysql with Java

    Hi there,
    I have a problem which i cannot find documented information regarding. The Problem is as Follows:
    I have a Java Application which connects to a Mysql Database. I need to create a CD distribution such that a single user could installed the application and run it. I know how to create a jar executable file. However, How do i deploy the mysql database i have create? Can somebody please provide me with information regarding deploying standalone desktop application which connects to databases?
    Please Help
    James

    We also had this problem...
    If you can change db's, I'd recommend Hypersonic SQL. Either way you should try using an install packager like installanywhere. If you use installanywhere standard you can run executables(the mysql installer) and custom code(to create your db). Although if you use hypersonic you can use the free version of installanywhere as you only need to copy the jar files across.

  • Generating CSV file with column names and data from the MySQL with JAVA

    Hi all,
    Give small example on ...
    How can I add column names and data to a CSV from from MySQL.
    like
    example
    sequence_no, time_date, col_name, col_name
    123, 27-apr-2004, data, data
    234, 27-apr-2004, data, data
    Pls give small exeample on this.
    Thanks & Regards
    Rama Krishna

    Hello Rama Krishna,
    Check this code:
    Example below exports data from MySQL Select query to CSV file.
    testtable structure
    CREATE TABLE testtable
    (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    text varchar(45) NOT NULL,
    price integer not null);
    Application takes path of output file as an argument.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    public class automateExport {
        public static void main(String[] args) {
            DBase db = new DBase();
            Connection conn = db.connect(
                    "jdbc:mysql://localhost:3306/test","root","caspian");
            if (args.length != 1) {
                System.out.println(
                        "Usage: java automateExport [outputfile path] ");
                return;
            db.exportData(conn,args[0]);
    class DBase {
        public DBase() {
        public Connection connect(String db_connect_str,
                String db_userid, String db_password) {
            Connection conn;
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(db_connect_str,
                        db_userid, db_password);
            } catch(Exception e) {
                e.printStackTrace();
                conn = null;
            return conn;
        public void exportData(Connection conn,String filename) {
            Statement stmt;
            String query;
            try {
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                //For comma separated file
                query = "SELECT id,text,price into OUTFILE  '"+filename+
                        "' FIELDS TERMINATED BY ',' FROM testtable t";
                stmt.executeQuery(query);
            } catch(Exception e) {
                e.printStackTrace();
                stmt = null;
    Greetings,
    Praveen Gudapati

  • How to get a photo into mySql with java

    I wonder how I can get a photo from a client-macine through web, into a mySql database. Communications too the web-user is going through a Servlet who is runnin in a Server, where the mySql database are too.
    I haved tryed this code-sequense but it dosent seems to work
    public void acceptInput( String overskrift, String ingress, String artikkel, String forfatter,
    String bildeTekst, String picture )throws SQLException{
    try{
    String ny = "";
    PreparedStatement pstmt = null;
    File file = null;
    if( !picture.equals( "" ) ){
    file = new File( picture );
    if( file.isFile() ){
    ny = "insert into NEWS values( NULL, ?, ?, ?, ?, ?, NULL,'"
    year "-" + month+ "-" day "')";
    System.out.println( "Er if if testen som tester om det er en fil" + file.length() );
    FileInputStream fileIn = new FileInputStream( file );
    pstmt.setBinaryStream(6, fileIn, (int)file.length() );
    fileIn.close();
    }//End of if( file.isFile() )
    }//End of if( !picture.equals( "" ) )
    else if( picture.equals( "" ) || !file.isFile() ){
    ny = "insert into NEWS values( NULL, ?, ?, ?, ?, ?, NULL,'"
    year "-" + month+ "-" day "')";
    }//End of else if(....)
    pstmt = dbKobling.prepareStatement( ny );
    pstmt.setString(1 , overskrift );
    pstmt.setString(2, ingress );
    pstmt.setString(3, artikkel );
    pstmt.setString(4, forfatter );
    pstmt.setString(5, bildeTekst );
    pstmt.executeUpdate();
    pstmt.close();
    }//End of try-block
    catch( Exception e ){
    JOptionPane.showMessageDialog(null, "Class:News.java Metode:acceptInput(...) " + e.getMessage() +
    ".", "Det har skjedd en feil !!!", 1);
    }//End of catch( Exeption e )
    }//End of method acceptInput
    I hope somone can help me :-)
    paulsep

    FileInputStream fileIn = new FileInputStream( file );
    pstmt.setBinaryStream(6, fileIn, (int)file.length() );
    fileIn.close();Almost correct! Just don't close the stream before the executeUpdate() method tries to use it.

  • [JAVA] problems with java and mysql

    Hi, i have already installed php + mysql and work's them fine, but i want to install java + mysql. I have downloaded eclipse and installed its, that's ok. I have download tomcat and, that's ok. I have download module jconnector and have copied the file .jar in the java home and set classpath. Run and compiled this source that's ok. At runtime the program ask: Impossible connection at the database, why ? It's the source of program:
    [JAVA]
    import java.sql.*;
    public class connessione {
    private String nomeDB; // Nome del Database a cui connettersi
    private String nomeUtente; // Nome utente utilizzato per la connessione al Database
    private String pwdUtente; // Password usata per la connessione al Database
    private String errore; // Raccoglie informazioni riguardo l'ultima eccezione sollevata
    private Connection db; // La connessione col Database
    private boolean connesso; // Flag che indica se la connessione � attiva o meno
    public connessione(String nomeDB) { this(nomeDB, "", ""); }
    public connessione(String nomeDB, String nomeUtente, String pwdUtente) {
    this.nomeDB = nomeDB;
    this.nomeUtente = nomeUtente;
    this.pwdUtente = pwdUtente;
    connesso = false;
    errore = "";
    // Apre la connessione con il Database
    public boolean connetti() {
    connesso = false;
    try {
    // Carico il driver JDBC per la connessione con il database MySQL
    Class.forName("com.mysql.jdbc.Driver");
    // Controllo che il nome del Database non sia nulla
    if (!nomeDB.equals("")) {
    // Controllo se il nome utente va usato o meno per la connessione
    if (nomeUtente.equals("")) {
    // La connessione non richiede nome utente e password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    } else {
    // La connessione richiede nome utente, controllo se necessita anche della password
    if (pwdUtente.equals("")) {
    // La connessione non necessita di password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente);
    } else {
    // La connessione necessita della password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente + "&password=" + pwdUtente);
    // La connessione � avvenuta con successo
    connesso = true;
    } else {
    System.out.println("Manca il nome del database!!");
    System.out.println("Scrivere il nome del database da utilizzare all'interno del file \"config.xml\"");
    System.exit(0);
    } catch (Exception e) { errore = e.getMessage(); }
    return connesso;
    public static void main(String [] args) {
    connessione a=new connessione("asta","root","");
    if(a.connetti())
    System.out.println("Connessione al database riuscita");
    else
    System.out.println("Connessione al database non riuscita");
    [JAVA]

    With this line I always pass the username and password also:
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB, useName, Password);
    Make sure you create your users in MySQL with the correct permissions

  • How to handle blob data with java and mysql and hibernate

    Dear all,
    I am using java 1.6 and mysql 5.5 and hibernate 3.0 . Some time i use blob data type . Earlier my project's data base was oracle 10g but now i am converting it to Mysql and now i am facing problem to save and fetch blob data to mysql database . Can anybody give me the source code for blob handling with java+Mysql+Hibernate
    now my code is :--
    ==================================================
    *.hbm.xml :--
    <property name="image" column="IMAGE" type="com.shrisure.server.usertype.BinaryBlobType" insert="true" update="true" lazy="false"/>
    ===================================================
    *.java :--
    package com.shrisure.server.usertype;
    import java.io.OutputStream;
    import java.io.Serializable;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Types;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;
    import oracle.sql.BLOB;
    import org.hibernate.HibernateException;
    import org.hibernate.usertype.UserType;
    import org.jboss.resource.adapter.jdbc.WrappedConnection;
    import com.google.gwt.user.client.rpc.IsSerializable;
    public class BinaryBlobType implements UserType, java.io.Serializable, IsSerializable {
    private static final long serialVersionUID = 1111222233331231L;
    public int[] sqlTypes() {
    return new int[] { Types.BLOB };
    public Class returnedClass() {
    return byte[].class;
    public boolean equals(Object x, Object y) {
    return (x == y) || (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    BLOB tempBlob = null;
    WrappedConnection wc = null;
    try {
    if (value != null) {
    Connection oracleConnection = st.getConnection();
    if (oracleConnection instanceof oracle.jdbc.driver.OracleConnection) {
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    if (oracleConnection instanceof org.jboss.resource.adapter.jdbc.WrappedConnection) {
    InitialContext ctx = new InitialContext();
    DataSource dataSource = (DataSource) ctx.lookup("java:/DefaultDS");
    Connection dsConn = dataSource.getConnection();
    wc = (WrappedConnection) dsConn;
    // with getUnderlying connection method , cast it to Oracle
    // Connection
    oracleConnection = wc.getUnderlyingConnection();
    tempBlob = BLOB.createTemporary(oracleConnection, true, BLOB.DURATION_SESSION);
    tempBlob.open(BLOB.MODE_READWRITE);
    OutputStream tempBlobWriter = tempBlob.getBinaryOutputStream();// setBinaryStream(1);
    tempBlobWriter.write((byte[]) value);
    tempBlobWriter.flush();
    tempBlobWriter.close();
    tempBlob.close();
    st.setBlob(index, tempBlob);
    } else {
    st.setBlob(index, BLOB.empty_lob());
    } catch (Exception exp) {
    if (tempBlob != null) {
    tempBlob.freeTemporary();
    exp.printStackTrace();
    st.setBlob(index, BLOB.empty_lob());
    // throw new RuntimeException();
    } finally {
    if (wc != null) {
    wc.close();
    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    final Blob blob = rs.getBlob(names[0]);
    return blob != null ? blob.getBytes(1, (int) blob.length()) : null;
    public Object deepCopy(Object value) {
    if (value == null)
    return null;
    byte[] bytes = (byte[]) value;
    byte[] result = new byte[bytes.length];
    System.arraycopy(bytes, 0, result, 0, bytes.length);
    return result;
    public boolean isMutable() {
    return true;
    public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return assemble(arg0, arg1);
    public Serializable disassemble(Object arg0) throws HibernateException {
    return disassemble(arg0);
    public int hashCode(Object arg0) throws HibernateException {
    return hashCode();
    public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
    return replace(arg0, arg1, arg2);
    =================================================================
    can anyone give me the source code for this BinaryBlobType.java according to mysql blob handling ..

    Moderator action: crosspost deleted.

  • The performance of management system with Java and MySQL

    Hi all,
    I want to develop one management application with Java and MySQL. However I am not sure which is a good way to design the system. The system has to deal with customers' data in the database.
    Should I create objects for every customers when application starts so that I do not need to access to the database often? Or
    Should I access to the database everytime the user want to deal with customer's data?
    Welcome for any suggestion.
    Thank you
    Pat

    Hi
    i i think u should go through MVC model or use connection pooling

  • Problem getting MySQL driver to work with JAVA

    Hi
    I have downloaded this driver for MySQL 'mysql-connector-java-3.0.16-ga-bin.jar' what should I do with this to make it work with my instalation of jdk1.3.1_15?
    I have placed it in the folder C:\jdk1.3.1_15\lib but I am getting the following error on compilation:
    MyClass.java:9: <identifier> expected
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    ^
    MyClass.java:9: cannot resolve symbol
    symbol : class forName
    location: class java.lang.Class
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    ^
    2 errors
    or am i doing something else wrong?

    Here's a snippet of the code I am using if this helps
    import java.util.*;
    import java.sql.*;
    class MyClass{
         Class.forName("com.mysql.jdbc.Driver").newInstance();
             Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/myDB?user=admin&password=admin", "", "");
         Statement statement = connection.createStatement();
         public void MyClass(){
                  // count the number of records in the database table
              ResultSet rsCount = statement.executeQuery("SELECT COUNT(*) AS tCount FROM myTable");     
              rsCount.first();
              int tCount = rsCount.getInt("tCount");
              rsCount.close();
    }

  • Problem with drawing info from mysql on an image with java

    I'm trying to draw info on a jpg with java, the info is in a mysql database with columns for what I want to draw and 2 columns for the x,y. I would be glad for any pointers, help and advice.
    1. Strangely the program draws all the info on the same spot in the image. I have no idea what I'm doing wrong.
    2. is there a way to tell java to continue drawing until there are no more rows in the database?
    I deleted the database info.
    Thanks for any help
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import java.util.*;
    import java.sql.*;
    import javax.sql.*;
    public class carte4 {
        public static void main(String[] args)throws IOException {
        try {
    Statement stmt;
    ResultSet rs;
    com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds;
    Connection conn2;
    ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
    ds.setServerName("");
    ds.setDatabaseName("");
    conn2 = ds.getConnection("", "");
    stmt = conn2.createStatement();
    rs = stmt.executeQuery( "select * from territoire");
    // process results
    while (rs.next()) {
    String nom = rs.getString("nomterritoire");
    String proprio = rs.getString("nomperso");
    int unites = rs.getInt("unites");
    int coordx = rs.getInt("coordonesX");
    int coordy = rs.getInt("coordonesY");
         BufferedImage image = ImageIO.read(new File(args[0]));
    //remplire les territoires
    Graphics graphics = image.getGraphics();
              graphics.setColor(Color.black);
              graphics.drawString("a" + proprio + unites, coordx, coordy);
            graphics.drawString("b" + proprio) + unites, coordx, coordy);
            graphics.drawString("c" + proprio + unites, coordx, coordy);
              // save modified image
              String format = "JPG";
              ImageIO.write(image, format, new File(args[1]));Message was edited by:
    retosteffen

    Bill,
    Another very helpful solution and I appreciate knowing how to fix it in both applications. Thanks!
    Wolf

  • MySQL and Java - getting program to work

    I am setting up mysql to run sql from a Java program on my pc at home and probably biting off more than I can chew. I get these messages when executing the java program ExecuteSQL.java:
    Exception in thread "main" java.lang.NoClassDefFoundError: Test2 <wrong name: MyProjects/test2/Test2>
    at java.lang.ClassLoader.defineClass0<Native Method>
    at java.lang.ClassLoader.defineClass<Unknown Source>
    at java.security.SecurityClassLoader.defineClass<Unknown Source>
    at java.net.URLClassLoader.defineClass<Unknown Source>
    at java.net.URLClassLoader.access$100<Unknown Source>
    at java.net.URLClassLoader$1.run<Unknown Source>
    at java.security.AccessController.ddPrivileged<Native Method>
    at java.lang.ClassLoader.findClass<Unknown Source>
    at java.lang.ClassLoader.loadClass<Unknown Source>
    at sun.misc.Launcher$AppClassLoader.loadClass<Unknown Source>
    at java.lang.ClassLoader.loadClass<Unknown Source>
    at java.lang.ClassLoader.loadClassInternal<Unknown Source>
    This is what I did.
    I created a folder on my C: drive named MySQL.
    I downloaded these two zip files form the MySQL website
         * mysql-connector-java-3.0.11-stable
         * mysql-4.0.18-win.zip
    Installed both of these in folder MySQL.
    I modified this line in the program ("ExecuteSQL" 1st pgm in chapter 17) I got from "Java Examples In a Nutshell" and compiled it into directory jwork.
    String driver = "com.mysql.jdbc.driver", url = "jdbc:mysql://", user = "", password = "";
    The readme file talks about putting a jar file in $JAVA_HOME/jre/lib/ext.
    the word "Java_Home" (I now know) is not literally the name but represents the
    name of the folder where the JDK to be used exists. So I put a copy of
    mysql-connector-java-3.0.11-stable-bin.jar in folder C:\JDK14/jre/lib/ext.
    Then I get a ClassNotFoundException error com.mysql.jdbc.driver.
    After finding
    http://forum.java.sun.com/thread.jsp?forum=31&thread=439796
    and
    http://forum.java.sun.com/thread.jsp?forum=31&thread=499888
    and others, I copied (a second copy) the jar file to the directory where I am create my java objects.
    Then I unzipped it to that directory, creating three folders that hold the unzipped objects.
    I tried executing the program again. I get the messages at the top of this post.
    The Manifest file is in one of the three folders unzipped to my java work directory.
    In the second of the two above threads, jsalonen says:
    the problem can be solved by mentioning mysql.jar in the Class-Path attribute
    in the manifest of the jar file:
    In this "manifest" file, there are only three lines and I added a fourth and it looks like this
    (there are two, one in directory MySQL\META-INF and one in directory jwork\META-INF:
    Manifest-Version: 1.0
    Ant-Version: Apache Ant 1.6.1
    Created-By: 1.4.0_01-b03 (Sun Microsystems Inc.)
    Main-Class:jwork\ExecuteSQL
    How do I "mention" mysql.jar in the class path attribute?
    In the index.list file (in the directory with the manifest file, do I need to add anything to refer that "com.mysql.jdbc.driver" is the driver?
    Do I need index.list in MySQL\META-INF ?
    Thank you for your help. The program ExecuteSQL follows.
    * Copyright (c) 2000 David Flanagan. All rights reserved.
    * This code is from the book Java Examples in a Nutshell, 2nd Edition.
    * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
    * You may study, use, and modify it for any non-commercial purpose.
    * You may distribute it non-commercially as long as you retain this notice.
    * For a commercial use license, or to purchase the book (recommended),
    * visit http://www.davidflanagan.com/javaexamples2.
    /** package com.davidflanagan.examples.sql; */
    import java.sql.*;
    import java.io.*;
    * A general-purpose SQL interpreter program.
    public class ExecuteSQL {
    public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {
    String driver = "com.mysql.jdbc.driver", url = "jdbc:mysql://",
    user = "", password = "";
    // Parse all the command-line arguments
    for(int n = 0; n < args.length; n++) {
    if (args[n].equals("-d")) driver = args[++n];
    else if (args[n].equals("-u")) user = args[++n];
    else if (args[n].equals("-p")) password = args[++n];
    else if (url == null) url = args[n];
    else throw new IllegalArgumentException("Unknown argument.");
    // The only required argument is the database URL.
    if (url == null)
    throw new IllegalArgumentException("No database specified");
    // If the user specified the classname for the DB driver, load
    // that class dynamically. This gives the driver the opportunity
    // to register itself with the DriverManager.
    if (driver != null) Class.forName(driver);
    // Now open a connection the specified database, using the
    // user-specified username and password, if any. The driver
    // manager will try all of the DB drivers it knows about to try to
    // parse the URL and connect to the DB server.
    conn = DriverManager.getConnection(url, user, password);
    // Now create the statement object we'll use to talk to the DB
    Statement s = conn.createStatement();
    // Get a stream to read from the console
    BufferedReader in =
              new BufferedReader(new InputStreamReader(System.in));
    // Loop forever, reading the user's queries and executing them
    while(true) {
    System.out.print("sql> "); // prompt the user
    System.out.flush(); // make the prompt appear now.
    String sql = in.readLine(); // get a line of input from user
    // Quit when the user types "quit".
    if ((sql == null) || sql.equals("quit")) break;
    // Ignore blank lines
    if (sql.length() == 0) continue;
    // Now, execute the user's line of SQL and display results.
    try {
    // We don't know if this is a query or some kind of
    // update, so we use execute() instead of executeQuery()
    // or executeUpdate() If the return value is true, it was
    // a query, else an update.
    boolean status = s.execute(sql);
              // Some complex SQL queries can return more than one set
              // of results, so loop until there are no more results
    do {
    if (status) { // it was a query and returns a ResultSet
    ResultSet rs = s.getResultSet(); // Get results
    printResultsTable(rs, System.out); // Display them
    else {
    // If the SQL command that was executed was some
    // kind of update rather than a query, then it
    // doesn't return a ResultSet. Instead, we just
    // print the number of rows that were affected.
    int numUpdates = s.getUpdateCount();
    System.out.println("Ok. " + numUpdates +
                             " rows affected.");
    // Now go see if there are even more results, and
    // continue the results display loop if there are.
    status = s.getMoreResults();
    } while(status || s.getUpdateCount() != -1);
    // If a SQLException is thrown, display an error message.
    // Note that SQLExceptions can have a general message and a
    // DB-specific message returned by getSQLState()
    catch (SQLException e) {
    System.err.println("SQLException: " + e.getMessage()+ ":" +
                        e.getSQLState());
    // Each time through this loop, check to see if there were any
    // warnings. Note that there can be a whole chain of warnings.
    finally { // print out any warnings that occurred
              SQLWarning w;
    for(w=conn.getWarnings(); w != null; w=w.getNextWarning())
    System.err.println("WARNING: " + w.getMessage() +
                             ":" + w.getSQLState());
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
    System.err.println(e);
    if (e instanceof SQLException)
    System.err.println("SQL State: " +
                        ((SQLException)e).getSQLState());
    System.err.println("Usage: java ExecuteSQL [-d <driver>] " +
                   "[-u <user>] [-p <password>] <database URL>");
    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
    try { conn.close(); } catch (Exception e) {}
    * This method attempts to output the contents of a ResultSet in a
    * textual table. It relies on the ResultSetMetaData class, but a fair
    * bit of the code is simple string manipulation.
    static void printResultsTable(ResultSet rs, OutputStream output)
         throws SQLException
    // Set up the output stream
    PrintWriter out = new PrintWriter(output);
    // Get some "meta data" (column names, etc.) about the results
    ResultSetMetaData metadata = rs.getMetaData();
    // Variables to hold important data about the table to be displayed
    int numcols = metadata.getColumnCount(); // how many columns
    String[] labels = new String[numcols]; // the column labels
    int[] colwidths = new int[numcols]; // the width of each
    int[] colpos = new int[numcols]; // start position of each
    int linewidth; // total width of table
    // Figure out how wide the columns are, where each one begins,
    // how wide each row of the table will be, etc.
    linewidth = 1; // for the initial '|'.
    for(int i = 0; i < numcols; i++) {             // for each column
    colpos[i] = linewidth; // save its position
    labels[i] = metadata.getColumnLabel(i+1); // get its label
    // Get the column width. If the db doesn't report one, guess
    // 30 characters. Then check the length of the label, and use
    // it if it is larger than the column width
    int size = metadata.getColumnDisplaySize(i+1);
    if (size == -1) size = 30; // Some drivers return -1...
         if (size > 500) size = 30; // Don't allow unreasonable sizes
    int labelsize = labels.length();
    if (labelsize > size) size = labelsize;
    colwidths[i] = size + 1; // save the column the size
    linewidth += colwidths[i] + 2; // increment total size
    // Create a horizontal divider line we use in the table.
    // Also create a blank line that is the initial value of each
    // line of the table
    StringBuffer divider = new StringBuffer(linewidth);
    StringBuffer blankline = new StringBuffer(linewidth);
    for(int i = 0; i < linewidth; i++) {
    divider.insert(i, '-');
    blankline.insert(i, " ");
    // Put special marks in the divider line at the column positions
    for(int i=0; i<numcols; i++) divider.setCharAt(colpos[i]-1,'+');
    divider.setCharAt(linewidth-1, '+');
    // Begin the table output with a divider line
    out.println(divider);
    // The next line of the table contains the column labels.
    // Begin with a blank line, and put the column names and column
    // divider characters "|" into it. overwrite() is defined below.
    StringBuffer line = new StringBuffer(blankline.toString());
    line.setCharAt(0, '|');
    for(int i = 0; i < numcols; i++) {
    int pos = colpos[i] + 1 + (colwidths[i]-labels[i].length())/2;
    overwrite(line, pos, labels[i]);
    overwrite(line, colpos[i] + colwidths[i], " |");
    // Then output the line of column labels and another divider
    out.println(line);
    out.println(divider);
    // Now, output the table data. Loop through the ResultSet, using
    // the next() method to get the rows one at a time. Obtain the
    // value of each column with getObject(), and output it, much as
    // we did for the column labels above.
    while(rs.next()) {
    line = new StringBuffer(blankline.toString());
    line.setCharAt(0, '|');
    for(int i = 0; i < numcols; i++) {
    Object value = rs.getObject(i+1);
              if (value != null)
              overwrite(line, colpos[i] + 1, value.toString().trim());
    overwrite(line, colpos[i] + colwidths[i], " |");
    out.println(line);
    // Finally, end the table with one last divider line.
    out.println(divider);
    out.flush();
    /** This utility method is used when printing the table of results */
    static void overwrite(StringBuffer b, int pos, String s) {
    int slen = s.length(); // string length
    int blen = b.length(); // buffer length
    if (pos+slen > blen) slen = blen-pos; // does it fit?
    for(int i = 0; i < slen; i++) // copy string into buffer
    b.setCharAt(pos+i, s.charAt(i));

    Don't put those JARs in the lib/ext directory. Only language extensions (e.g., packages that start with "javax") belong in there.
    Learn how to set the CLASSPATH properly for starters:
    http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html
    You might want to look at the JDBC tutorial, too:
    http://java.sun.com/docs/books/tutorial/jdbc/
    Do one thing at a time. Get the program to work, then worry about packaging it into an executable JAR.

  • Using mysql-connector-java-5.0.5 from oracle's java procedure.

    I need to write the java procedure in Oracle, which will get connection to mySQL server and put some data into it. I am using official mysql-connector-java-5.0.5 driver for this job. Java class for this job work well outside the Oracle. The problem is:
    When I try to import jar file of mysql connectior it fail son resolving inside the Oracle db. How can I get access to mysql from Oracle?

    Thanks for this quick reply!!
    --When adding a connection and clicking 'Test' in the end of the wizard or when right-click on the connection and click 'connect'.
    Also, I've just noticed this: when I start IDE using jdev.exe I'm getting:
    java.lang.NullPointerException at oracle.jdevimpl.cm.dt.DatabaseAddin._registerIDEObjects(DatabaseAddin.java:353)
    at oracle.jdevimpl.cm.dt.DatabaseAddin.initialize(DatabaseAddin.java:155
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddin(AddinManage
    rImpl.java:425)
    at oracle.ideimpl.extension.AddinManagerImpl.initializeAddins(AddinManag
    erImpl.java:240)
    at oracle.ideimpl.extension.AddinManagerImpl.initProductAndUserAddins(Ad
    dinManagerImpl.java:154)
    at oracle.ide.IdeCore.initProductAndUserAddins(IdeCore.java:1431)
    at oracle.ide.IdeCore.startupImpl(IdeCore.java:1196)
    at oracle.ide.Ide.startup(Ide.java:674)
    at oracle.ideimpl.Main.start(Main.java:49)
    at oracle.ideimpl.Main.main(Main.java:25)
    Does not look right to me.
    I've never tried to add a DB connection under this IDE installation earlier.
    Just yeasterday I've created a project with some DB related (mySQL and Hibernate) libraries, although it compiled fine.

  • WebLogic 8.1 SP4 fails to start on FC4 with Java (GNU libgcj)

    Hi,
    When I use the Java JVM which comes with FC4, my WebLogic server (8.1 SP4) will not boot.
    NB It boots with the BEA jdk (also a 1.4.2 version)
    I choose the FC4 Java JVM, because then the MySQL's driver mysql-connector-java-3.0.16-ga-bin.jar will work. (Checked
    with a simple java program). But the WebLogic server runs off the rails.
    Here is the output of ./startWebLogic.sh :
    CLASSPATH=/usr/lib/jvm/java//lib/tools.jar:/opt/bea/weblogic81/server/lib/weblogic_sp.jar:/opt/bea/weblogic81/server/lib/weblogic.jar:/opt/bea/weblogic81/server/lib/mysql-connector-java-3.0.16-ga-bin.jar:/usr/lib/jvm/java//jre/lib/rt.jar:/opt/bea/weblogic81/server/lib/webservices.jar:
    PATH=/opt/bea/weblogic81/server/bin:/usr/lib/jvm/java//jre/bin:/usr/lib/jvm/java//bin:/usr/kerberos/bin:/usr/lib/courier/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/opt/jboss/bin:/home/harry/bin
    *** This the actual start of the WebLogic server **
    /usr/lib/jvm/java//bin/java -client -Xms32m -Xmx200m -XX:MaxPermSize=128m -Xverify:none -Dweblogic.Name=ISA -Dweblogic.ProductionModeEnabled=false -Djava.security.policy=/opt/bea/weblogic81/server/lib/weblogic.policy weblogic.Server
    *** The error message *** ***************************************************************************
    The WebLogic Server did not start up properly.
    java.lang.NullPointerException
    at javax.security.auth.login.LoginContext.LoginContext(java.lang.String, javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler) (/usr/lib/libgcj.so.6.0.0)
    at javax.security.auth.login.LoginContext.LoginContext(java.lang.String, javax.security.auth.callback.CallbackHandler) (/usr/lib/libgcj.so.6.0.0)
    at weblogic.security.internal.ServerAuthenticate.main(java.lang.String[]) (Unknown Source)
    at weblogic.t3.srvr.T3Srvr.run(java.lang.String[]) (Unknown Source)
    at weblogic.Server.main(java.lang.String[]) (Unknown Source)
    at gnu.java.lang.MainThread.call_main() (/usr/lib/libgcj.so.6.0.0)
    at gnu.java.lang.MainThread.run() (/usr/lib/libgcj.so.6.0.0)

    The Exceptions before originate from a small java program.
    I tested the working of the mysql driver with a small java program as I got these Exceptions when testing a Connection Pool in WebLogic.
    The problems with WebLogic and databases started when I used the pointBaseConsole.sh script.
    SQL State: 08004
    SQL-Server rejected eshtablishment of SQL-connection. Pointbase Server may not be running at localhost at port 9092. NB Of course I have started the Poinbase server. It says it was listening at port 9092
    I get these Exceptions both wtih opening an existing (demo) database as with creating a new one.
    Here is the small java program: It is compiled/run with java (1.4.x) from FC4 and with java 1.5 from SUN. Both versions worked successfully.
    import java.sql.*;
    public class MySQLTest {
    public static void main (String[] args) throws SQLException {
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    Connection conn = DriverManager.getConnection(
    "jdbc:mysql://my.site.com/botenlijst",
    "myUser", "myPassword");
    // The query we will execute
    final String query = "SELECT * FROM fotos";
    // Create a statement
    Statement stmt = conn.createStatement ();
    // Execute the query
    ResultSet rset = stmt.executeQuery (query);
    // Dump the result
    String s = " --- ";
    while (rset.next ()) {
    System.out.println ( rset.getString(1) + s + rset.getString(2) );
    conn.close();
    }

  • How to fetch data from Mysql with SSL.

    I am using jdk1.5 and mysql 5.0.
    How to fetch data from Mysql with SSL
    I am using url = jdbc:mysql://localhost/database?useSSL=true&requireSSL=true.
    It shows error. how to fetch

    I have created certificate in mysql and checked in mysql.
    mysql>\s
    SSL: Cipher in use is DHE-RSA-AES256-SHA
    but through ssl how to fetch data in java.

Maybe you are looking for