Steps cor connectivity java and mysql

Hi can any one list the steps for the connectivity of java & mysql.
jdk1.6 & mysql5

1) Learn JDBC: http://java.sun.com/docs/books/tutorial/jdbc/index.html
2) Obtain the MySQL JDBC driver: http://www.mysql.com/products/connector/j/
3) Read the MySQL JDBC driver reference documentation: http://dev.mysql.com/doc/refman/6.0/en/connector-j-reference.html

Similar Messages

  • Few question about Java and MySQL connection

    Hi!
    I have some problems with creating connection between Java and MySQL.
    I followed the restrictions in mysql-connector-java.jar' readme, I set the CLASSPATH :
    CLASSPATH=.;D:/mysql/mysql-connector-java.jar;
    I copied this jar file to the right place (descripted above), and I used the right steps to load it:
    Class.forName('com.mysql.jdbc.Driver"); and it throws a ClassNotFoundException
    Why? All the paths are correct, everything is on the right place.... I dont know why.
    When I installed the JBuilder8, and copied the jar file to JBuilder8/jdk4/jre/lib/ext it worked without any CLASSPATH in enviromental variables.
    If I want to run my program on machines where are not JBuilder, what should I do?
    Please help, if you can.
    Thanks,
    henpanta

    Yeah. So if I compiled my program with JBuilder to an .exe file, I cant run it on other machines, if the jar file isnt in the same place?
    If I tried your advice, java -classpath mymainclass I got the next message:
    main class not found. Believe me, its there. :(

  • 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,

  • 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.
    %

  • 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

  • Unable to connect JSP and MySQL

    Hi, I am new to this forum
    I've started developing web pages using JSP
    I've the problem connecting JSP and MySQL database. I've created the page that retrive records from mysql table. But the connection fail to access to database it gives me this error:
    org.apache.jasper.JasperException: Exception in JSP: /retreive_book.jsp:15
    The code is:
    12: <%
    13: //Class.forName("com.mysql.jdbc.Driver").newInstance();
    14: Class.forName("org.gjt.mm.mysql.Driver");
    15: connection = DriverManager.getConnection(connectionURL,"","");
    16: statement = connection.createStatement();
    17: rs = statement.executeQuery("SELECT * FROM books_detail");
    18: %>
    And the connectionURL parameter has this value:
    String connectionURL = "jdbc:mysql://localhost:3306/books?username=;password=";
    root cause msg is:
    java.sql.SQLException: Invalid authorization specification: Access denied for user 'nobody'@'localhost' (using password: NO)
    Please can anyone help me. It is 3 days now trying to do that but not succeded yet

    Hi
    Yes It is true that my MySQl installation its username is root. So how should put that in the url. Cause I did that but it didn.t work
    String connectionURL= "jdbc:mysql://localhost:3306/books?username=root;password=";
    If I write in that manner is it correct for root username or should I put a single quote
    Thanks

  • BAPI step by step to connect JAVA for catsdb table

    BAPI step by step to connect JAVA for catsdb table,
    Points will be rewarded,
    full points with example of catsdb table in bapi for JCO JAVA
    Thank you,
    Regards,
    Jagrut BharatKumar Shukla

    Hi,
    Check the thread..
    https://forums.sdn.sap.com/click.jspa?searchID=3587428&messageID=3647918
    Regards,
    Omkar.

  • How to connect Java and Microsoft SQL Server 2000

    hi,
    could anyone please teach me how to connect Java and SQL Sever 2000?? if possible could you guys provide me with an example??? i could hardly find any relevant resources about it...
    Thanks ~!

    thanks for the information...
    by the way hv any working module on it?? i'm new to
    both Java and Microsoft SQL Server... Thanks againFirst things first... you should read this:
    http://java.sun.com/docs/books/tutorial/jdbc/
    This is microsofts official JDBC Driver: http://www.microsoft.com/sql/downloads/jdbcregister.asp
    Install it and the documentation has some usage examples

  • Wrong use of Java and Mysql?

    I currently have a dedicated database server which runs MySQL. On the MySQL server I have 15 tables with the InnoDB engine.
    These tables all have a column called "last_sync". Whenever a tablerow is updated by a java client, the "last_sync" column is refreshed.
    Other java clients will query these tables with a query that looks something like this
    "Select count(*) from table where last_sync > (currenttime-5 seconds) and last_sync <= (currenttime)"
    So much for the background info. To stresstest my server, and see how much queries per second he can handle,
    I installed Super Smack (http://vegan.net/tony/supersmack/). Super smack is a stresstest tool which can be given 2 start-up parameters.
    These parameters say how many clients/threads should connect and how many times the query should be ran. When installed it
    is possible to alter the stress query by editting the "select-key.smack" file. I did so and placed a query that is equal to the above statement.
    Super-smack (as well as MySQL Administrator and Innotop) tells me that it can execute 50K queries per second when I use a single connection.
    When I use two connections I get roughly 88K. This is logical since my server is a dual-core machine. I run super smack on my DB server.
    Now, whenever I try to stresstest my server with a java written test, I can barely get to 10k queries per second on a single connection.
    The app is being runned on the DB server as well. Furthermore when I add another connection, the limit stays at 10k queries.
    When monitoring the connection threads with MySQL Administrator the connection threads
    are often "sleeping" while, when I run the SuperSmack test they are constantly in use.
    Another detail, the connection threads also gives info what it's doing ("Executing query", "Writing to net" etc.). I occasionally see "Rollback", which is strange
    since my stress query is not failing in my stress application.
    To make this complete, I've uploaded my little test along with the SQL creation code to the following URL: HERE
    It should work straight out of the box. Naturally the table creation query should be ran and the connection settings specified in the java file.
    Basically the one thing I cannot understand is why supersmack runs a factor 5-8 faster than my java test while they are
    using the exact same table and are executed on the exact same machine. This however limits out the possibility of it being a database config setting.
    Im personally guessing im incorrectly using transactions or the MySQL connector/j is giving problems.
    I understand this might take some effort, so i'll try to add more dukes than a regular post.
    -Edit. Was under the assumption that you could add more than 10 duke points.
    Thanks in advance
    Edited by: killingdjef on Mar 25, 2009 6:52 AM
    Edited by: killingdjef on Mar 25, 2009 10:28 AM

    killingdjef wrote:
    10K can be perfect, however, when I run Supersmack and see that my database server can handle 8 times more queries per second on the exact same table with the exact same query,
    I'm beginning to wonder if im doing something incorrect or if i'm missing something crucial.
    I have no clue whats a reasonable amount of queries per second is for a dedicated innodb server
    but based on the benchmark test im thinking I can squeeze out more.
    The stresstest isnt representational for a single client. Its merely a simulation how many clients could be served.
    The higher the queries per second, the more clients that can be served. Im trying to find out what the limit would be.I am quite aware of what impact means in terms of client processing. That however isn't the point. The point is that you intend to serve a market of some sort and support some reasonable growth. It is pointless to try to do more than that.
    If you have enough "clients" running directly against that database to generate 10k queries a second then your architecture (and thus design and implementation) is very likely flawed.
    For example
    1. What happens to all of those clients when the database goes down either accidently or on purpose?
    2. Those clients are hitting the database direct, and I don't see how you are going to get enough clients like that without internet consumers. And you absolutely do not want to expose the database that way.
    3. Conversely say you have a call center with 2000 support people, which is a huge call center. There is no way that number could generate even close to 10k a second.
    4. A comparable txn business model is credit card processing and a sustained speed like that would be sufficient to handle all of the credit card transaction business in the US during the peak xmas season. With extra left over.
    Not to mention that you didn't address the network problem at all. Note that the numbers I outlines above doesn't allow any bandwidth for the data to get into the server in the first place.
    And inserts will take more time than queries.
    But as I already said, if you are using transaction then that will have an impact. Connections/threads will as well.

  • Unable to connect java to mysql

    I have installed mysql on my linux machine (i didnt modify any default configuration settings, just using the default settings). And in my lan, from another machine in windows from my java code i am trying to connect to mysql of linux, but donno why i get connection refused error. Can someone help me to figure what the steps i am missing or need to do?

    Thanks for your reply. I do not have any network managers. I have installed mysql on my linux machine and also started mysql. Now in remote machine i have downloaded mysql-connector-java-5.0.4-bin.jar file and using this jar file my java code is trying open a connection to mysql.
              try {
                   Class.forName("com.mysql.jdbc.Driver");
              }catch(Exception ce) {ce.printStackTrace();}
              try {
                   Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.20.160:3306/mysql","root","new_password");192.168.20.160 is the linux machine where mysql is running.
    But of no use, i get connection refused error. following is stacktrace
    SQLException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.net.SocketException
    MESSAGE: java.net.ConnectException: Connection refused: connect
    STACKTRACE:
    java.net.SocketException: java.net.ConnectException: Connection refused: connect
         at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
         at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
         at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
         at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
         at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
         at java.sql.DriverManager.getConnection(DriverManager.java:525)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at TestDriver.main(TestDriver.java:11)
    ** END NESTED EXCEPTION **
    Last packet sent to the server was 63 ms ago.
    SQLState: 08S01
    VendorError: 0

  • 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.

  • Cannot connect java to mysql server 2000

    I was unable to connect to the mysql server 2000 with the jcreator.
    The following exception was thrown:
    java.net.SocketException
    MESSAGE: java.net.ConnectException: Connection refused: connect
    STACKTRACE:
    java.net.SocketException: java.net.ConnectException: Connection refused: connect at com.mysql.jdbs.StandardSocketFactory.connect<StandardSocketFactory.java:156?
    at com.mysql.jdbc.MysqlIO.<init><MysqlIO.java:284>
    ** END NESTED EXCEPTION **
    and the code i used was :
    package com.stardeveloper.example;
    import java.sql.*;
    public class JCustomer {
    public static void main(String args[]) {
    Connection con = null;
    try {
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection("jdbc:mysql:///Customer", "user", " ");
    if(!con.isClosed())
    System.out.println("Successfully connected to MySQL server...");
    } catch(Exception e) {
    System.err.println("Exception: " + e.getMessage());
    } finally {
    try {
    if(con != null)
    con.close();
    } catch(SQLException e) {}
    I donot have any user and pwd for the MYsql server, it is local host connection and window authentication is used.

    eventhough it is local ,you may need to specify dns/localhost/ip with port number.
    otherwise you can use myODBC driver which is freely available in mysql website. you can connect to the database using Data source Name, just like using any other ODBC connectivity.

  • JDeveloper setup steps for pdk java and portlet container - ver 10.1.2

    Hi fellows,
    Can someone please point to some really not-confusing guide to setting up pdk java and portlet containers on jdeveloper 10.1.2.
    Problem is, I went through several documentation links and they keep pointing around to steps that are followed if you wish to have a stand-alone OC4J. JDeveloper 10.1.2 also had a preconfigured OC4J with it. I wish to make use of that and configure it for Oracle Portal editings for version 10.1.2.
    thank you for your help.

    I have some documentation that I tried following:
    For PDK-Java installation, here is the link to documentation.
    http://www.oracle.com/technetwork/middleware/ias/installing-089002.html
    However, what is confusing is what to do if you just wish to use the preconfigured OC4J container that comes with Jdeveloper 10.1.2.
    Experts, can you please clear this out please?
    Thanks!

  • [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

  • 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.

Maybe you are looking for