Connectivity java with mySql

Hi
Can any one tell me how should i connect my java application with mySql database here is the small code which i written.
import java.sql.*;
class tryjdbc
     public static void main(String[] args) throws Exception
     try
          Class.forName("com.mysql.jdbc.Driver").newInstance();
          String connectionURL = "jdbc:mysql://localhost:3306/learn?user=root;password=";
          Connection connection = DriverManager.getConnection(connectionURL, "root", "");
          Statement statement = connection.createStatement();
          ResultSet rs = statement.executeQuery("Select ecode from emp");
          while (rs.next())
               System.out.println(rs.getString("ecode"));
          catch (Exception e){
               System.out.println(e);
Can any one please tell me the error there is no eror in compiling but at run time it gives error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Thanks in advance
Dhiraj

Hi Dhiraj,
String connectionURL = "jdbc:mysql://localhost:3306/learn?user=root;password=";
Connection connection = DriverManager.getConnection(connectionURL, "root", "");
It seems to be your trying to pass twice of your properties details. One from through URL and another from by pasing the parameters on getConnection() method. Better to avoid to use two place in same application. and one more thing I want to confirm r u using "stable" Driver or "alpha" Driver.
Raju

Similar Messages

  • Can' t connect Java with MySQL

    My goal is to connect Java with MySQL. I found many solutions on Internet, but I always get the same mistake:
    SQLException: No suitable driver
    SQLState: 08001
    VendorError: 0MySQL works fine alone or with php.Only thing left me to think is that the installed versions are not compatible for this mysql-connector-java-5.0.4
    I don't believe that could be a reason.
    Installed versions are:
    Apache Tomcat 5.5.20 Server
    Apache HTTP Server 2.2.4
    PHP 5.2.0
    MySQL 5.2
    jre 1.5.0_11
    jdk1.5.0_11
    Apache Tomacat JK2 connector Version: 1.2.20 File Name: mod_jk-apache-2.2.3.so
    mysql-connector-java-5.0.4
    I also set connector in class path: C:\mysql-connector-java-5.0.4;C:\mysql-connector-java-5.0.4\mysql-connector-java-5.0.4-bin.jar;C:\mysql-connector-java-5.0.4\src\com\mysql\jdbc
    For installation I used manulas from:
    http://apacheguide.org/jsp.php
    http://doc.51windows.net/mysql/?url=/MySQL/ch23s03.html
    Here is also a test code in java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
       public class Connect
           public static void main (String[] args)
               Connection conn = null;
               try {
        conn =
           DriverManager.getConnection("jdbc:mysql://localhost/first_test" +
                                       "user=monty&password=greatsqldb");
        // Do something with the Connection
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
       }i'm desperate, please help or tell me someone who'll know the answer.
    Thank You in advance

    hey buddy .. it seems yr code is wrong .. in getconnection () method u should also specify the port ,which u r not doing ...
    the default port for MySQL is 3306 ... see below i am giving you a sample code ... its working fine .. and dont forget to put the MySQL driver jar path in to classpath and also copy the jar into common/lib folder of your tomcat ....
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class MySQLConnectionTest {
         public static void main(String[] args) {
    new MySQLConnectionTest().connTest();
    public void connTest() {
              String tableName = "portfolio"; //change as per setting
              String hostName = "10.81.9.39"; // please change for the target database ip or hostname
              String dbPort = "3306"; //change if not using the default
              String dbName = "tradingsystem"; //change as per the given DB name
              String username = "root"; //change as per setting
              String password = "password"; //change as per setting
              System.out.println("before try");
              Double data=0.0;
         Double data1=0.0;
              try {
    Class.forName("org.gjt.mm.mysql.Driver");
                   System.out.println("before driver manager");
    Connection conn = DriverManager.getConnection("jdbc:mysql://"+hostName+":"+dbPort+"/"+dbName, username, password);
    String query1 = "select * from "+tableName+" where User_id='trader1' and Stock_Type='Equity'";
    System.out.println("quesry1="+query1);
    Statement stmt = conn.createStatement();
    ResultSet rs1 = stmt.executeQuery(query1);
    while(rs1.next())
         System.out.println("hiiiiii for rs1");
         System.out.println(rs1);
         Quantity=(Integer)rs1.getObject(5);
         MarketPrice=(Double) rs1.getObject(8);
         data=Quantity*MarketPrice;
         data1+=data;
         System.out.println("data1="+data1);
         i=0;
    rs1.close();
    stmt.close();
    conn.close();
    } catch (ClassNotFoundException e) {
    e.printStackTrace(System.err);
    } catch (SQLException e) {
    e.printStackTrace(System.err);
    i hope it will work for u...
    cheers,

  • Hoe to connect java with mysql 5.0

    I have installed the new Os. in that RHE-5 Os is there, now I want that java can connect ot mysql but , its not able connect with mysql so please guide me.

    1) download mysql connector/J JDBC driver from mysql.com
    2) put the driver jar somewhere where you can put it in the classpath of your application
    3) use proper setup code to connect to the database (search google, tons of examples)
    If at any step you have no clue what I am talking about, you need a good book to help you further.

  • Date Problem in Java with MySql

    Hello
    I am using Java with Mysql.I want to enter date in some in my format(YYYY:MM:DD:HH:MM:SS), this thing i have convert using format class and format class return date in String and iwwnat to insert this value in MySQL Table,So i want to know how can i convert String value in Date for Mysql is their inbuild function for converting string into date in mysql.
    Regards
    Anupam S

    Use PreparedStatement and SimpleDateFormat classes
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=%2BPreparedStatement+%2BSimpleDateFormat+&qp=siteforumid%3Ajava48&chooseCat=allJava&col=developer-forums&site=dev

  • An error occured when connecting java with Ms Access

    Hello Everybody
    I am a new developer in java and want to connect java with Microsoft Access
    i am using JCreator LE
    My code is to insert 3 records for 3 members and then save them in DB and retrieve the information
    Here is the code
    import java.sql.*;
    public class Project3 {
        public static void main(String[] args) {
             try {
                  System.out.println("Beginning Connection");
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String accessFileName = "Information";
                String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ="+accessFileName+".mdb;PWD=";
                Connection con = DriverManager.getConnection( connURL ,"","");
                Statement stmt = con.createStatement();
                System.out.println("Connection done successfully");
                stmt.execute("Create table Member(Name String,ID Integer)");
                stmt.execute("insert into Member values ('Joe','1234')");
                stmt.execute(" select * from Member");
                ResultSet rs=stmt.getResultSet();
                if (rs != null)
                     while (rs.next()){
                          System.out.println("Name: "+rs.getString("Name")+ "ID: " + rs.getString("ID"));
                stmt.close();
                con.close();
                catch (Exception e) {
                System.out.println("An error Occurred in Connecting with the DB " );
    }and the error is
    Beginning Connection
    Connection done successfully
    An error Occurred in Connecting with the DB
    it didn't insert information in the DB

    Well, thank u i have traced the error and fx it
    but
    how to modify the code and keep the user entering 3 values and search for the entered values??
    Here is the correct code
    import java.sql.*;
    public class Project3 {
        public static void main(String[] args) {
             try {
                  System.out.println("Beginning Connection");
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String accessFileName = "jdbc:odbc:Project";
                String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ="+accessFileName+".mdb;PWD=";
                Connection con = DriverManager.getConnection( accessFileName);
                Statement stmt = con.createStatement();
                System.out.println("Connection done successfully");
                stmt.execute("Create table Member(Name String,ID Integer)");
                stmt.execute("insert into Member values ('Joe','1234')");
                stmt.execute(" select * from Member");
                ResultSet rs=stmt.getResultSet();
                if (rs != null)
                     while (rs.next()){
                          System.out.println("Name: "+rs.getString("Name")+ "ID: " + rs.getString("ID"));
                stmt.close();
                con.close();
                catch (Exception err) {err.printStackTrace();}
    }

  • How to connect APEX with MYSQL via Apex's Database link

    How do i connect APEX with MYSQL via Apex's Database link? The OBE doesn't go into specific detail about how to link the two.
    can someone please elaborate on what these are and where i can find them in mysql:
    Database Link Name      
    Connect To Schema      
    Password      
    Remote Hostname or IP      
    Remote Host Port      
    SID or Service Name      
    I need to link to mysql database so I can set up a 3D pie chart in apex

    Hi jononioo
    A database link is a device for connecting between Oracle database instances only. Oracle does have a method for connecting to other database systems (Transparent Gateway) but this is restricted to other commercial databases and I don't believe there is a gateway for Mysql. (I could be wrong)
    I don't know Mysql but maybe there is some way to push data to the Oracle instance. Other than that, is there any reason why the data has to reside in the Mysql database?
    Regards
    Andre

  • Unable to connect JAVA with Oracle

    I have jdk1.6 and oracle installed on my machine but unable to connect java with database
    have classes12.jar and ojdbc14.jar
    my environmental variables in respect to this are :
    JAVA_HOME= C:\Java\jdk1.6.0_04
    JRE_HOME=C:\Java\jdk1.6.0_04
    PATH=J:\oracle\ora92\lib;
    J:\oracle\ora92\bin;
    C:\Program Files\Oracle\jre\1.3.1\bin;
    C:\Program Files\Oracle\jre\1.1.8\bin
    CLASSPATH=J:\oracle\ora92\jdk\jre\bin\JdbcOdbc.dll;
    J:\oracle\ora92\jdbc\lib\classes12.jar;
    J:\oracle\ora92\jdbc\lib\ojdbc14.jar
    The code is
    import java.sql.*; public class dat1 {               public static void main(String[] args)throws SQLException,ClassNotFoundException {         try     {     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     Class.forName("com.oracle.jdbc.OracleDriver");     } catch (ClassNotFoundException e) { System.out.println("unable to load driver"); return; }     } }
    the error message is
    Error in thread "main" java.lang.NoClassDefFoundError
    Please Help Me
    Thanks For Reading
    Thanks a lot in Advance For your ANSWERS

    maybe if you asked nicely instead of ordering people around we might tell you.
    As it is all you're going to hear is that you don't need both those jars, as they contain different versions of the same driver.
    I'm not going to tell you which you need, as you should have the documentation to tell you that. But then you also should have the documentation to tell you how to set your classpath properly and you failed to read that too.

  • How to connect java with database without any dsn.

    is there any way to connect java with database with out creating any dsn..like we do in ado in vb by providing provider.

    Sure use a type 4 driver. No DSN.

  • How to connect java in mysql....

    how to connect java in mysql.... help me guys
    am newbie...

    http://www.mysql.com/products/connector/j/
    download the JDBC driver and read the docs.
    if you don't know JDBC, Google for "Sun JDBC tutorial" and study it.
    don't ask for sample code. there's plenty out there.
    %

  • How to connect java with oracle

    can any body show me the code of how to connect java with oracle database.
    thank you

    To configure Oracle JDBC:
    1. Add Oracle JDBC JAR file classes12.zip or ojdbc14.zip to classpath.
    2. Load and register the JDBC driver.
    Class.forName("oracle.jdbc.driver.OracleDriver");
    3. Obtain a connection:
    String url="jdbc:oracle:thin:@<host>:1521:<database>
    Connection con = DriverManager.getConnection(url,
    "myLogin", "myPassword");
    4. Create a SQL statement.
    Statement stmt = con.createStatement();
    5. Obtain a result set.
    ResultSet rs = stmt.executeQuery(
    "SELECT ...");

  • Connecting JAVA with  Video Card

    Hai,...
    Can someone tell me how to connect Java with a video card (like Matrox, dec-link, etc)?
    Because i want to display a video using that video card to a TV monitor.
    Is there any tutorial about this? and about connecting JAVA with other device?
    Thank you,
    Billy

    Hai,...
    Can someone tell me how to connect Java with a video card (like Matrox, dec-link, etc)?
    Because i want to display a video using that video card to a TV monitor.
    Is there any tutorial about this? and about connecting JAVA with other device?
    Thank you,
    Billy

  • Connect JAVA with ABAP

    Hi,
    I have a requirement in my project to connect Java with ABAP. I want to access ABAP tables from my java application. I am not sure but I think we can use SAP JDBC drivers to do that.
    I found this link to connect JAVA with ABAP  :
    SAP DB JDBC Driver
    My doubt from this link is where can I get the Host Name for the sandbox system I am using and what is the Database Schema name for the tables created using se11.
    Regards,
    Prateek

    Hi
    If you have direct connection to data base then  you can use
    the JDBC driver for the data base that is in use (We have oracle).
    But usually you have to go through the application server this mean you have to use "SAP Java Connector" that connect to SAP using RFC .
    Talk to your basis people.
    Regards.

  • Connecting java with macromedia shockwave

    I wanna make an application that connect java with macromedia shockwave, for doing example...
    administering a web chat., or a game. I dont wanna sound like a fool a dummy but i think java is safer than macromedia in security aspects.
    I wanna do like a multicap application, macromedia is the visual chat, means people dont have to download all the jre to their computer, and a app in java , in the server that manages the users in the chat, the users permissions, and so. like a better "habbo hotel" chat
    "The goal of Flex is to allow Web application developers to quickly and easily build rich Internet applications. In a multi-tiered model, Flex applications serve as the presentation tier."

    have you tried searching the forums for threads relevant to your problem? There
    are many discussions in the forum regarding this one. :)

  • JAVA with MYSQL problem

    i am using jdk1.6.0_02,apache tomcat 5.5.23 ,mysql integrated with redhat linux EE 4 and.mysql connector java 5.0.7.bin.jar.
    look at the the following java program
    import java.sql.*;
    public class TestMysql
    public static void main(String args[])
    try
    String driver = "com.mysql.jdbc.Driver";
    Class.forName( driver );
    String url = "jdbc:mysql://localhost/test";
    DriverManager.getConnection( url, "root", "mysql" );
    catch( Exception x )
    {      x.printStackTrace();
    i got the following exception
    java.sql.SQLException: Access denied for user 'root'@'localhost.localdomain' (us *** password:
    YES)
    at com.mysql.jdbc.SQLError.createSQLException(java.lang.String, java.lang.Str ***, int)
    (Unknown Source)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(int) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket() (Unknown Source)
    at com.mysql.jdbc.MysqlIO.secureAuth411(com.mysql.jdbc.Buffer, int, java.lang .String,
    java.lang.String, java.lang.String, boolean) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.doHandshake(java.lang.String, java.lang.String, jav a.lang.String)
    (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Prop erties,
    java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Pr operties)
    (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Propertie s)
    (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String, java.lang.String, j
    ava.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at Connect.main(java.lang.String[]) (Unknown Source)
    access denied problem. but the user name and password are correct. i can login to mysql by using
    the same username and password.
    but when connecting through java , i can't ? what is the problem?
    can u help me.?
    actually i am working in JSP. and when i got this problem, i created a small java program for testing.
    here i am submitting the java program.

    friend please put your code inside
       // your code goes here  it will more readable and other can solve it better.
    ==================
    and your problem tells that you must set access permission inside
    mySQL server.
    or try with creating new User with password.
    EnJOY.
    Ghanshyam
    Edited by: Ghanshyam on Sep 28, 2007 4:13 PM

  • Java with MYSQL in Linux

    i am using JSP in Linux Platform. when i connected to mysql with mysql driver for odbc by using the following code,
    import java.sql.*;
    public class TestMysql
    public static void main(String args[]) {
    try {
              Connection con;
              String connStr = "jdbc:mysql://localhost/test?user=root&password=mysql";
              Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
              System.out.println("OK");
              con = DriverManager.getConnection( connStr );
              System.out.println("Again OK");
    catch( Exception x )
    x.printStackTrace();
    i got the following exception
    OK
    java.sql.SQLException: Error during query: Unexpected Exception: java.io.CharConversionException message given: null
    Nested Stack Trace:
    ** BEGIN NESTED EXCEPTION **
    java.io.CharConversionException
    STACKTRACE:
    java.io.CharConversionException
    at gnu.gcj.convert.Input_iconv.read(char[], int, int) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.String.init(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at java.lang.String.String(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at com.mysql.jdbc.SingleByteCharsetConverter.SingleByteCharsetConverter(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.SingleByteCharsetConverter.initCharset(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.SingleByteCharsetConverter.getInstance(java.lang.String, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.Connection.getCharsetConverter(java.lang.String) (Unknown Source)
    at com.mysql.jdbc.StringUtils.getBytes(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.Buffer.writeStringNoNull(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(com.mysql.jdbc.Statement, java.lang.String, java.lang.String, com.mysql.jdbc.Buffer, int, com.mysql.jdbc.Connection, int, int, boolean, java.lang.String, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
    at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at TestMysql.main(java.lang.String[]) (Unknown Source)
    ** END NESTED EXCEPTION **
    at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
    at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at TestMysql.main(java.lang.String[]) (Unknown Source)
    i have the database, hello.
    The same code works well in Windows, But in Linux, the above exception.
    By using the username root and password mysql , i can connect to mysql directly from the mysql prompt.
    Pls help me..
    I have already put the query 'access denied problem in Mysql' some day before. from the reply, i made some changes in user table(ie. set the password for [email protected].).After this change, this new Exception came..
    The structure of my mysql.user table is
    #     host                         user          password
    1     localhost                    root          68d4f47c49a579c9
    2     localhost.localdomain          root          68d4f47c49a579c9
    3     localhost.localdomain          
    4     localhost          
    Pls help me.
    Edited by: SUMESHBABU_R on Sep 30, 2007 11:36 PM

    Well, at least the trace tells me that this issue is to be tracked back to the core of the MySQL JDBC driver and the Linux's implementation of JVM. It might be worth the effort to post this issue at their website/forum/issuetracker. It might also be worth the effort to tryout the newer MySQL JDBC driver 5.1, as it is written specific for JDK 6.0 (while MySQL JDBC driver 5.0 is targeted at JDK 5.0).

Maybe you are looking for

  • All drives busy, how to free one for tape labeling?

    Our backups are currently wedged because of a media shortfall. We have a dedicated mediafamily for full backups and all of the tapes for that pool have been exhausted. All of the drives are have backups running (paused, really) and waiting for tapes.

  • Coldfusion 11 java/jre ssl mutual auth api calls.  Help with coldfusion/java logs.

    Hello, I am here because I have exhausted my Coldfusion/Java ssl keystore certs trouble shooting abilities.  Here is the issue. I am developing a Coldfusion 11 application that must make api calls to Chase payconnexion SOAP services. I am using the c

  • Query output

    Hi, I have SERVER_UID_RPT table with the following details. table consist of records of entry & exit for the employees. But i want to query those user which have only entry granted but the exit granted entry is not there in table for the user & vice

  • Automating Testing of Business Objects Reports...

    I am a new user to empirix e-Tester and I need some assistance understanding how the program captures events during recording... I am trying to build a very simple test to use against the Business Objects Reporting package. Basically, I have the foll

  • What is the keycommand manager and how do you locate it?

    Greetings.  I am brand new to Mac and I was trying to figure out what shortcut I could use to reposition the playhead in Adobe AfterEffects to the beginning because my keyboard doesn't have a home key.  In the process of searching, I found some artic