Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JDBC Connecting with MySql

Like Connectivity with Oracle, we can connect java application with the mysql database. The following 5 steps are required to perform database connectivity.

  • 1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
  • 2. URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/silan 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 silan is the database name.
  • 3. Username: The default username for the mysql database is root.
  • 4. Password: Password is given by the user at the time of installing the mysql database. In this example, we are going to use password as the password.

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

  • 1. create database silan;
  • 2. use silan;
  • 3. create table custoemr(cid int(10),cname varchar(40),cage int(3))

Example:

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

MysqlConDemo.java
import java.sql.*;
class MysqlConDemo
{
public static void main(String[] args) throws Exception
{
    Class.forName(“com.mysql.jdbc.Driver”);
    Connection con=DriverManager.getConnection(“jdbc:mysql://
localhost:3306/silan”,
    “root”,”password”);
    //here silan is database name, root is username and password is 
password name
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery(“select * from customer”);
    while(rs.next())
    System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+rs.
getString(3));
    con.close();
    }
}

The above example will retrieve all the records from customer table.


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc







 PreviousNext