Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to connect MySql Database using JDBC API in Java ?.

A Simple Program demonstrating how to connect MySql Database using JDBC API in Java

package com.hubberspot.jdbc.example;

import java.sql.*;
import java.io.*;

public class JdbcConnectivity
{
  public static void main(String[] args) throws SQLException
  {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    String userName = "root";
    String password = "sa";
    String url = "jdbc:mysql://localhost:3306/links";
    try
    {
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection 
                            (url, userName, password);
      
      if(conn!=null)
        System.out.println("Connection successful..");
      
      stmt = conn.createStatement();
      rs = stmt.executeQuery("Select * from student");
      
      while(rs.next())
      {
       System.out.print("Roll Number = " + rs.getInt(3));
       System.out.print(" First Name = " + rs.getString(1));
       System.out.println(" Last Name = " + rs.getString(2));
      }
      
      conn.close();
    
    }
    catch(Exception e) 
    {
       System.out.println(e);}
    }
}    


Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot