Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Databases / December 2006

Tip: Looking for answers? Try searching our database.

Connecting to mysql via Java

Thread view: 
yankeerivera@yahoo.com - 04 Dec 2006 18:10 GMT
Hi, I am new to mysql. I need to connect to a mysql server from a Java
application. Can someone share some sample code or point me to the
right place for a sample?

I am assuming that I'll have to download a Mysql driver and I'll be
able to use the usual java.sql.* classes.
David Harper - 04 Dec 2006 19:08 GMT
> Hi, I am new to mysql. I need to connect to a mysql server from a Java
> application. Can someone share some sample code or point me to the
> right place for a sample?
>
> I am assuming that I'll have to download a Mysql driver and I'll be
> able to use the usual java.sql.* classes.

You might find it helpful to read a couple of books:

"Learning Java"

  http://www.oreilly.com/catalog/learnjava2/

"Database Programming with JDBC & Java"

  http://www.oreilly.com/catalog/jdbc2/index.html

The first book contains plenty of examples of Java techniques, such as
opening a file and reading it a line at a time.

The second book focusses on database programming with Java.

You should then read the documentation about Connector/J, the JDBC
library for MySQL:

  http://dev.mysql.com/doc/refman/4.1/en/connector-j.html

This provides advice about how to obtain and install the latest version
of Connector/J, and examples showing how to connect to MySQL and send
commands and queries to the MySQL server.

In a recent thread on this subject, Jeff Summers also recommended "MySQL
and Java Developers Guide" by Matthews, Cole, and Gradecki, from Wiley.
 Mark Matthews is the principal developer of Connector/J, so you'll be
learning from the expert.

Good luck with your project.

David Harper
Cambridge, England
Dr.Zoidberb - 04 Dec 2006 20:24 GMT
> Hi, I am new to mysql. I need to connect to a mysql server from a Java
> application. Can someone share some sample code or point me to the
> right place for a sample?
>
> I am assuming that I'll have to download a Mysql driver and I'll be
> able to use the usual java.sql.* classes.

That is correct you will need the Java Connector found at
http://dev.mysql.com/downloads

The basic flow for talking to MySQL via java is:

1. Load the Driver
2. Make the Connection
3. Make the query
4. Do something with results

Sample/Starter code:

public static boolean load_mysql_driver()
{
    try {
         // The newInstance() call is a work around for some
         // broken Java implementations

         Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception ex) {
                  System.err.println(ex);// handle the error
         return false;
    }
    return true;
}

public static Connection connect_mysql(String hostname, String
database, String username, String password)
{
    Connection conn;
       try {

       conn = DriverManager.getConnection("jdbc:mysql://" + hostname +
"/"+ database +"?user="+username+"&password=" + password);

       } catch (SQLException ex) {
           // handle any errors
               System.err.println("SQLException: " + ex.getMessage());
               System.err.println("SQLState: " + ex.getSQLState());
               System.err.println("VendorError: " + ex.getErrorCode());
            return null;
       }

       return conn;
}

public static void main (String args[])
{
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

       if(load_mysql_driver())
        {
            System.out.println("Unable to load MySQL Driver!");
            return;
        }

        conn = connect_mysql("hostname", "database", "username", "password");

        try
        {
            stmt = conn.createStatement();
            rs = stmt.executeQuery( "SELECT * FROM myTable t" );

            while(rs.next())
            {
                //Do something with the results
            }
        }
        catch(SQLException e)
        {
            System.err.println(e);
            return;
        }
}

That's the very basics. If you google for MySQL java examples you
should find a bunch.
jcsnippets.atspace.com - 05 Dec 2006 13:10 GMT
yankeerivera@yahoo.com wrote in news:1165255854.409987.82500
@f1g2000cwa.googlegroups.com:

> Hi, I am new to mysql. I need to connect to a mysql server from a Java
> application. Can someone share some sample code or point me to the
> right place for a sample?
>
> I am assuming that I'll have to download a Mysql driver and I'll be
> able to use the usual java.sql.* classes.

Hi,

All the steps you need to take to connect to a MySQL database, and some
sample code can be found here:
http://jcsnippets.atspace.com/java/database/connect-to-mysql-database.html

Best regards,

JayCee
Signature

http://jcsnippets.atspace.com/
a collection of source code, tips and tricks



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.