Database Connection using MySQL or Oracle

Java Database Connectivity with MySQL

  • Create Database in MySQL

create database Edu;
  • Create Table in MySQL

create table emp(id int(10),name varchar(40),age int(3));
  • Register the Driver class

Class.forName("com.mysql.jdbc.Driver");
  • Create connection

Connection con=DriverManager.getConnection(  "jdbc:mysql://localhost:3306/Edu","root","root");
  • Create statement

Statement stmt=con.createStatement();
  • Execute queries

ResultSet rs=stmt.executeQuery("select * from emp");
  • Display records

while(rs.next())
{
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
}
  • Close connection

con.close();

Java Database Connectivity with Oracle

  • Create table

create table emp(id number(10),name varchar2(40),age number(3));

  • Register the Driver class

Class.forName("oracle.jdbc.driver.OracleDriver");

  • Create connection

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

  • Create statement

Statement stmt=con.createStatement();

  • Execute queries

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

  • Display records

while(rs.next())
{
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
}

  • Close connection

con.close();

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form