Write a program to create simple JDBC application to insert and retrieve records from mysql database. code example

Example: Write a program to create simple JDBC application to insert and retrieve records from mysql database.

import java.sql.*;

public class SqlDb {
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/student_database";
    static final String USER = "root";
    static final String PASS = "";

    public static void main(String[] args) throws Exception {
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement s = conn.createStatement();) {
            Class.forName(JDBC_DRIVER);
            System.out.println("Connected to database...");
            s.execute(
                    "create table student( enroll_no varchar(15) primary key,stud_name varchar(20),stud_address varchar(30) )");
            s.execute("insert into student values('181230107017','sudip','navsari')");
            s.execute("insert into student values('181230107005','bhavyesh','surat')");
            ResultSet rs = s.executeQuery("select * from student");
            if (rs != null) // if rs == null, then there is no record in ResultSet to show
                while (rs.next()) // By this line we will step through our data row-by-row
                {
                    System.out.println("______");
                    System.out.println("Enrollnment Id : " + rs.getString(1));
                    System.out.println("Name : " + rs.getString(2));
                    System.out.println("Address : " + rs.getString(3));
                    System.out.println("______");
                }
        } catch (SQLException err) {
            System.out.println("ERROR : " + err);
        }
    }
}

Tags:

Java Example