Connecting java and mysql database

For connecting java application with the mysql database, you need to
follow 5 steps to perform database connectivity.

In this example we are using MySql as the database. So we need to know
following informations for the mysql database:

1. *Driver class: * The driver class for the mysql database is
2. *Connection URL: * The connection URL for the mysql database is
*jdbc:mysql://localhost:3306/test* where jdbc is the API, mysql is
the database, localhost is the server name on which mysql is
running, we may also use IP address, 3306 is the port number and
sonoo is the database name. We may use any database, in such case,
you need to replace the test with your database name.
3. *Username: * The default username for the mysql database is *root*.
4. *Password: * Password is given by the user at the time of installing
the mysql database. In this example, we are going to use root as the

Let’s first create a table in the mysql database, but before creating
table, we need to create database first.

create database test;
use test;
create table emp(id int(10),name varchar(40),age int(3));

Here’s the code

import java.sql.*;
class MysqlCon
public static void main(String args[]){

Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,”root”,”root”);

//here test is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery(“select * from emp”);

System.out.println(rs.getInt(1)+”  “+rs.getString(2)+”  “+rs.getString(3));


}catch(Exception e){ System.out.println(e);}


To connect java application with the mysql database mysqlconnector.jar file is required to be loaded.

We have to manually download the mysqlconnector.jar from the internet and paste the mysqlconnector.jar file in jre/lib/ext folder

Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste

I use sabayon 10 and path in my os is /etc/java-config-2/current-system-vm/jre/lib/ext/mysqlconnector.jar

Now compile the code and run it.

Thank You for reading


About pacesettergraam

A good and realistic person

Posted on January 20, 2013, in Java, sabayon and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: