Saturday, 20 February 2016

Database connection in java with it's example

## Database Connection: 

There are few step's to how to get connection MySql database and also explain with example.



Five step of Database connection



Step 1: Drive class: It means drive class for the mysql database is Class.forName("com.mysql.jdbc.Drive"); 


Step 2: Connection Url:   It means the connection URL for the database is 
connection con=DriverManager.getConnection("jdbc://localhost:3306/Database","UserName","Password");


Step 3: UserName: UserName is root default for the mysql database.


Step 4: Password: Here Password is provided by the user at time of installing the mysql database.






Here we put it's  example for how to connect your 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/demo", "root", "root");

//Please enter in place of demo your database name, root is username and password

 //create database statement
Statement stmt=con.createStatement();
 
ResultSet rs=stmt.executeQuery("select * from admin");

// Here enter in place of admin your class name.
 
while(rs.next())
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
 
con.close();
 
}
catch(Exception e)
{
         System.out.println(e);
}
 
}

}

Result : Now your database is sucessfully conected with mysql database. now here you and do any thing like update, delete...etc