Pin It

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 :


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot