Example to Connect Java Application with 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 com.mysql.jdbc.Driver.
  2. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/mithilesh 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 mithilesh is the database name. We may use any database, in such case, you need to replace the mithilesh with your database name.
  3. Username: The default username for the mysql database is root.
  4. Password: use root as the password.

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

 

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


Example to Connect Java Application with mysql database

In this example, mithilesh is the database name, root is the username and password.

Example Java Application with mysql database


import java.sql.*;  
class MysqlCon
{  
public static void main(String args[]){  
try{  
Class.forName(" com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mithilesh","root","root");  
//here mithilesh is database name, root is username and password Statement
	stmt=con.createStatement(); ResultSet rs=stmt.executeQuery( "select * from emp");  

while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
con.close();  
}
catch(Exception)
{
 System.out.println(e);
}  
}  
}

Second Example of DSN Program

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

	{
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			Connection con=DriverManager.getConnection("jdbc:odbc:mk");
			Statement stmt=con.createStatement();
			ResultSet rset=stmt.executeQuery("select * from emp");
			while(rset.next())
			{
	                         System.out.println(rset.getInt(1)+"\t"+rset.getString(2)+
                                         "\t"+rset.getString(3)+"\t"+rset.getInt(4));

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